﻿using Module_Debug.Hardware;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.IO.Ports;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Windows.Forms;
//using JOJO_gamma;

namespace Module_Debug.VDDIC_Gamma
{
    public partial class ILI8818_Gamma : Form
    {
        CaSDK CaSDKObj = new CaSDK();
        CRC16 CRCData = new CRC16();
        Gamma_Addr GAMMAs = new Gamma_Addr();

        private ushort[] gamma_r = new ushort[24];
        private ushort[] gamma_g = new ushort[24];
        private ushort[] gamma_b = new ushort[24];

        private bool Listening = false;//是否没有执行完invoke相关操作   
        private bool IClosing = false;//是否正在关闭串口，执行Application.DoEvents，并阻止再次invoke 
        private List<byte> buffer = new List<byte>(2048);//默认分配1/16页内存，并始终限制不允许超过
        private double[,] D_lums;//目标值-单色
        private double[] D_lum;//目标值-白色

        private int index = 0;
        private int flag1 = 1; //lum
        private int flag2 = 1; //x
        private int flag3 = 1; //y
        private byte[] Send_buf = new byte[1];
        private byte[] Rec_tmp = new byte[1];

        //创建类型为Person的对象集合
        List<Setting.Gamma_Property> Diven_Gamma = new List<Setting.Gamma_Property>();
        List<Setting.Offset_Property> Diven_Offset = new List<Setting.Offset_Property>();
        string Path = System.AppDomain.CurrentDomain.BaseDirectory + "ILI8818" + ".txt";
        public byte retRegData = 0;

        private static bool Gamma_adjust_timeout_flag = false;
        //Gamma绑点定义
        //private int[] Parttern_IC69091 = new int[34] { 255, 247, 239, 231, 223, 215, 207, 199, 191, 183, 175, 159, 143, 127, 111, 95, 79, 63, 55, 47, 39, 31, 23, 19, 17, 15, 13, 11, 9, 7, 5, 3, 1, 0 };

        frmMain frmHelp = null;


        public ILI8818_Gamma()
        {
            InitializeComponent();
        }

        private void ILI8818_Gamma_Load(object sender, EventArgs e)
        {
            IC_comboBox.SelectedIndex = 0;
        }
        public ILI8818_Gamma(frmMain ILI8818_Gamma)
        {
            frmHelp = ILI8818_Gamma;
            InitializeComponent();
            frmHelp.Child_window_hide_already = true;
            frmHelp.Child_Gamma_Window_Open_Enable = false;//防止重复开启子窗体            
        }
        //ILI8818 监听卸载
        private void ILI8818_Gamma_FormClosed(object sender, FormClosedEventArgs e)
        {
            ////frmHelp.comPort.Close()
            frmHelp.comPort.DataReceived -= new SerialDataReceivedEventHandler(ILI8818_DataReceived);
            frmHelp.comPort.DataReceived += new SerialDataReceivedEventHandler(frmHelp.SerialPort1_DataReceived);
            ////frmHelp.comPort.Open();
            frmHelp.textBox1.Text = frmHelp.textBox1.Text + "ILI8818_Gamma_FormClosed！\r\n";
            frmHelp.Child_Gamma_Window_Open_Enable = true; //允许其他子窗体打开
            frmHelp.Child_window_hide_already = false;
            frmHelp.IC_comboBox.Enabled = true;
        }

        private void ILI8818_Gamma_VisibleChanged(object sender, EventArgs e)
        {
            if (frmHelp.Child_window_hide_already == false) //子窗体已开启标识
            {
                ////frmHelp.comPort.Close()
                frmHelp.comPort.DataReceived -= new SerialDataReceivedEventHandler(ILI8818_DataReceived);
                frmHelp.comPort.DataReceived += new SerialDataReceivedEventHandler(frmHelp.SerialPort1_DataReceived);
                ////frmHelp.comPort.Open();
                frmHelp.textBox1.Text = frmHelp.textBox1.Text + "ILI8818_Gamma_FormHide！\r\n";
                frmHelp.Child_window_hide_already = true; //子窗体已隐藏标识
            }
            else
            {
                frmHelp.comPort.DataReceived -= new SerialDataReceivedEventHandler(frmHelp.SerialPort1_DataReceived);
                frmHelp.comPort.DataReceived += new SerialDataReceivedEventHandler(ILI8818_DataReceived);
                frmHelp.textBox1.Text = frmHelp.textBox1.Text + "ILI8818_Gamma_FormOpened！\r\n";
                frmHelp.Child_window_hide_already = false; //子窗体已开启标识
            }
        }
        //串口接收
        private void ILI8818_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)//Getting data from Comm Port
        {
            if (IClosing) return;
            try
            {
                Listening = true;//设置标记，说明我已经开始处理数据，一会儿要使用系统UI的。         
                int n = frmHelp.comPort.BytesToRead;
                byte[] buf = new byte[n];
                byte data;

                frmHelp.comPort.Read(buf, 0, n);//读取缓冲数据     
                bool data_1_catched = false;//缓存记录数据是否捕获到    
                buffer.AddRange(buf);
                byte CRCH, CRCL;
                if (buffer.Count > 3)
                {
                    //  0x6F: ILI8818的Gamma读写、寄存器读写、OTP读写    设置  返回
                    if (buffer[0] == 0x6F && Setting.TempRecord.cmdLen > 0)
                    {
                        if (buffer.Count >= Setting.TempRecord.cmdLen)
                        {
                            Rec_tmp = new byte[Setting.TempRecord.cmdLen];
                            byte[] crcTemp = new byte[Setting.TempRecord.cmdLen];
                            buffer.CopyTo(0, crcTemp, 0, Setting.TempRecord.cmdLen);

                            CRCData.CalculateCrc16(crcTemp, out CRCH, out CRCL);
                            if (buffer[Setting.TempRecord.cmdLen - 2] != CRCH && buffer[Setting.TempRecord.cmdLen - 1] != CRCL)     //CRC校验出错
                            {
                                buffer.RemoveRange(0, buffer.Count);
                            }
                            else
                            {
                                buffer.CopyTo(0, Rec_tmp, 0, Setting.TempRecord.cmdLen);//复制一条完整数据到具体的数据缓存   
                                data_1_catched = true;
                                buffer.RemoveRange(0, Setting.TempRecord.cmdLen);//正确分析一条数据，从缓存中移除数据。 
                            }
                        }
                    }
                    //0x2F De-Mura 基本操作
                    else if (buffer[0] == 0x2F && (Setting.TempRecord.cmdLen > 0))
                    {
                        if (buffer.Count >= Setting.TempRecord.cmdLen)
                        {
                            Rec_tmp = new byte[Setting.TempRecord.cmdLen];
                            byte[] crcTemp = new byte[Setting.TempRecord.cmdLen];
                            buffer.CopyTo(0, crcTemp, 0, Setting.TempRecord.cmdLen);

                            CRCData.CalculateCrc16(crcTemp, out CRCH, out CRCL);
                            if (buffer[Setting.TempRecord.cmdLen - 2] != CRCH && buffer[Setting.TempRecord.cmdLen - 1] != CRCL)     //CRC校验出错
                            {
                                buffer.RemoveRange(0, buffer.Count);
                            }
                            else
                            {
                                buffer.CopyTo(0, Rec_tmp, 0, Setting.TempRecord.cmdLen);//复制一条完整数据到具体的数据缓存   
                                data_1_catched = true;
                                buffer.RemoveRange(0, buffer.Count);  //正确分析一条数据，从缓存中移除数据。  
                            }
                        }
                    }
                    else
                    {
                        buffer.RemoveRange(0, buffer.Count);
                    }
                }

                if (data_1_catched)
                {
                    this.Invoke((EventHandler)(delegate
                    {
                        frmHelp.T1.Enabled = false; //停止超时计数
                        if (Rec_tmp[0] == 0x6F)
                        {
                            switch (Rec_tmp[1])
                            {
                                case 0x01: { if (Rec_tmp[4] == 0x00) frmHelp.textBox1.Text = frmHelp.textBox1.Text + "写寄存器\tOK！\r\n"; } break;//寄存器写功能返回状态
                                case 0x02:
                                    {
                                        int i;
                                        string tmp = "";
                                        for (i = 3; i <= (Rec_tmp[2] + 1); i++)
                                        {
                                            tmp = tmp + String.Format("{0:X2}", Rec_tmp[i]) + ",";//16进制
                                        }
                                        tmp = tmp + String.Format("{0:X2}", Rec_tmp[i]);

                                        txt_Reg_Data_WR.Text = tmp;
                                        frmHelp.textBox1.Text = frmHelp.textBox1.Text + "寄存器\t读 OK！\r\n";
                                    }
                                    break;
                                case 0x03:
                                    {
                                        if (Rec_tmp[4] == 0x00) frmHelp.textBox1.Text = frmHelp.textBox1.Text + "OTP烧录\tOK！\r\n";
                                    }
                                    break;
                                case 0x23:
                                    {
                                        for (int i = 0; i < 24; i++)
                                        {
                                            RGBValue[i, 0] = ((Rec_tmp[2 * i + 4] & 0x0f) * 256 + Rec_tmp[2 * i + 5]);
                                            //R[4]=02;R[5]=10, 3'd256=3'h100;
                                        }
                                        for (int i = 0; i < 24; i++)
                                        {
                                            RGBValue[i, 1] = ((Rec_tmp[2 * i + 4 + 48] & 0x0f) * 256 + Rec_tmp[2 * i + 5 + 48]);
                                        }
                                        for (int i = 0; i < 24; i++)
                                        {
                                            RGBValue[i, 2] = ((Rec_tmp[2 * i + 4 + 96] & 0x0f) * 256 + Rec_tmp[2 * i + 5 + 96]);
                                        }

                                        for (int i = 0; i < 24; i++)
                                        {
                                            RGBValueSet(array2value, i, 0, 0);
                                            RGBValueSet(array2value, i, 1, 0);
                                            RGBValueSet(array2value, i, 2, 0);
                                        }

                                        frmHelp.textBox1.Text = frmHelp.textBox1.Text + "Gamma数据\t RGB全读 OK.\r\n";
                                    }
                                    break;
                                case 0x07:
                                    {
                                        if (Rec_tmp[4] == 0x00)
                                            frmHelp.textBox1.Text = frmHelp.textBox1.Text + "OTP Successful !";
                                        else
                                            frmHelp.textBox1.Text = frmHelp.textBox1.Text + "手动检查是否烧录成功。";
                                    }
                                    break;
                                case 0x08://Write Gamma
                                    {
                                        if (Rec_tmp[4] == 0x00)
                                            frmHelp.textBox1.Text = frmHelp.textBox1.Text + "GAMMA \t写 OK！\r\n";
                                        else if (Rec_tmp[4] == 0x02)
                                            frmHelp.textBox1.Text = frmHelp.textBox1.Text + "GAMMA \t写 ERROR！\r\n";
                                    }
                                    break;
                                case 0x09://Read Gamma  Rec_tmp[4]未定义
                                    {
                                        if (Setting.TempRecord.ILI8818_GammaCmdType == 0x03)//Red Register
                                        {

                                            {
                                                num_ILI8818_R0.Value = Decimal.Parse((Rec_tmp[4] & 0x0f).ToString()) * 256 + Decimal.Parse(Rec_tmp[5].ToString());//0x03,最大0x03ff，0x0f,最大0x07ff
                                                num_ILI8818_R1.Value = Decimal.Parse((Rec_tmp[6] & 0x0f).ToString()) * 256 + Decimal.Parse(Rec_tmp[7].ToString());
                                                num_ILI8818_R2.Value = Decimal.Parse((Rec_tmp[8] & 0x0f).ToString()) * 256 + Decimal.Parse(Rec_tmp[9].ToString());
                                                num_ILI8818_R3.Value = Decimal.Parse((Rec_tmp[10] & 0x0f).ToString()) * 256 + Decimal.Parse(Rec_tmp[11].ToString());
                                                num_ILI8818_R4.Value = Decimal.Parse((Rec_tmp[12] & 0x0f).ToString()) * 256 + Decimal.Parse(Rec_tmp[13].ToString());
                                                num_ILI8818_R5.Value = Decimal.Parse((Rec_tmp[14] & 0x0f).ToString()) * 256 + Decimal.Parse(Rec_tmp[15].ToString());
                                                num_ILI8818_R6.Value = Decimal.Parse((Rec_tmp[16] & 0x0f).ToString()) * 256 + Decimal.Parse(Rec_tmp[17].ToString());
                                                num_ILI8818_R7.Value = Decimal.Parse((Rec_tmp[18] & 0x0f).ToString()) * 256 + Decimal.Parse(Rec_tmp[19].ToString());
                                                num_ILI8818_R8.Value = Decimal.Parse((Rec_tmp[20] & 0x0f).ToString()) * 256 + Decimal.Parse(Rec_tmp[21].ToString());
                                                num_ILI8818_R9.Value = Decimal.Parse((Rec_tmp[22] & 0x0f).ToString()) * 256 + Decimal.Parse(Rec_tmp[23].ToString());
                                                num_ILI8818_R10.Value = Decimal.Parse((Rec_tmp[24] & 0x0f).ToString()) * 256 + Decimal.Parse(Rec_tmp[25].ToString());
                                                num_ILI8818_R11.Value = Decimal.Parse((Rec_tmp[26] & 0x0f).ToString()) * 256 + Decimal.Parse(Rec_tmp[27].ToString());

                                                num_ILI8818_R12.Value = Decimal.Parse((Rec_tmp[28] & 0x0f).ToString()) * 256 + Decimal.Parse(Rec_tmp[29].ToString());
                                                num_ILI8818_R13.Value = Decimal.Parse((Rec_tmp[30] & 0x0f).ToString()) * 256 + Decimal.Parse(Rec_tmp[31].ToString());
                                                num_ILI8818_R14.Value = Decimal.Parse((Rec_tmp[32] & 0x0f).ToString()) * 256 + Decimal.Parse(Rec_tmp[33].ToString());
                                                num_ILI8818_R15.Value = Decimal.Parse((Rec_tmp[34] & 0x0f).ToString()) * 256 + Decimal.Parse(Rec_tmp[35].ToString());
                                                num_ILI8818_R16.Value = Decimal.Parse((Rec_tmp[36] & 0x0f).ToString()) * 256 + Decimal.Parse(Rec_tmp[37].ToString());
                                                num_ILI8818_R17.Value = Decimal.Parse((Rec_tmp[38] & 0x0f).ToString()) * 256 + Decimal.Parse(Rec_tmp[39].ToString());
                                                num_ILI8818_R18.Value = Decimal.Parse((Rec_tmp[40] & 0x0f).ToString()) * 256 + Decimal.Parse(Rec_tmp[41].ToString());
                                                num_ILI8818_R19.Value = Decimal.Parse((Rec_tmp[42] & 0x0f).ToString()) * 256 + Decimal.Parse(Rec_tmp[43].ToString());
                                                num_ILI8818_R20.Value = Decimal.Parse((Rec_tmp[44] & 0x0f).ToString()) * 256 + Decimal.Parse(Rec_tmp[45].ToString());
                                                num_ILI8818_R21.Value = Decimal.Parse((Rec_tmp[46] & 0x0f).ToString()) * 256 + Decimal.Parse(Rec_tmp[47].ToString());
                                                num_ILI8818_R22.Value = Decimal.Parse((Rec_tmp[48] & 0x0f).ToString()) * 256 + Decimal.Parse(Rec_tmp[49].ToString());
                                                num_ILI8818_R23.Value = Decimal.Parse((Rec_tmp[50] & 0x0f).ToString()) * 256 + Decimal.Parse(Rec_tmp[51].ToString());


                                            }

                                            frmHelp.textBox1.Text = frmHelp.textBox1.Text + "红 Gamma数据\t读 OK！\r\n";
                                        }
                                        else if (Setting.TempRecord.ILI8818_GammaCmdType == 0x04)//Green Register
                                        {

                                            {
                                                num_ILI8818_G0.Value = Decimal.Parse((Rec_tmp[4] & 0x0f).ToString()) * 256 + Decimal.Parse(Rec_tmp[5].ToString());
                                                num_ILI8818_G1.Value = Decimal.Parse((Rec_tmp[6] & 0x0f).ToString()) * 256 + Decimal.Parse(Rec_tmp[7].ToString());
                                                num_ILI8818_G2.Value = Decimal.Parse((Rec_tmp[8] & 0x0f).ToString()) * 256 + Decimal.Parse(Rec_tmp[9].ToString());
                                                num_ILI8818_G3.Value = Decimal.Parse((Rec_tmp[10] & 0x0f).ToString()) * 256 + Decimal.Parse(Rec_tmp[11].ToString());
                                                num_ILI8818_G4.Value = Decimal.Parse((Rec_tmp[12] & 0x0f).ToString()) * 256 + Decimal.Parse(Rec_tmp[13].ToString());
                                                num_ILI8818_G5.Value = Decimal.Parse((Rec_tmp[14] & 0x0f).ToString()) * 256 + Decimal.Parse(Rec_tmp[15].ToString());
                                                num_ILI8818_G6.Value = Decimal.Parse((Rec_tmp[16] & 0x0f).ToString()) * 256 + Decimal.Parse(Rec_tmp[17].ToString());
                                                num_ILI8818_G7.Value = Decimal.Parse((Rec_tmp[18] & 0x0f).ToString()) * 256 + Decimal.Parse(Rec_tmp[19].ToString());
                                                num_ILI8818_G8.Value = Decimal.Parse((Rec_tmp[20] & 0x0f).ToString()) * 256 + Decimal.Parse(Rec_tmp[21].ToString());
                                                num_ILI8818_G9.Value = Decimal.Parse((Rec_tmp[22] & 0x0f).ToString()) * 256 + Decimal.Parse(Rec_tmp[23].ToString());
                                                num_ILI8818_G10.Value = Decimal.Parse((Rec_tmp[24] & 0x0f).ToString()) * 256 + Decimal.Parse(Rec_tmp[25].ToString());
                                                num_ILI8818_G11.Value = Decimal.Parse((Rec_tmp[26] & 0x0f).ToString()) * 256 + Decimal.Parse(Rec_tmp[27].ToString());

                                                num_ILI8818_G12.Value = Decimal.Parse((Rec_tmp[28] & 0x0f).ToString()) * 256 + Decimal.Parse(Rec_tmp[29].ToString());
                                                num_ILI8818_G13.Value = Decimal.Parse((Rec_tmp[30] & 0x0f).ToString()) * 256 + Decimal.Parse(Rec_tmp[31].ToString());
                                                num_ILI8818_G14.Value = Decimal.Parse((Rec_tmp[32] & 0x0f).ToString()) * 256 + Decimal.Parse(Rec_tmp[33].ToString());
                                                num_ILI8818_G15.Value = Decimal.Parse((Rec_tmp[34] & 0x0f).ToString()) * 256 + Decimal.Parse(Rec_tmp[35].ToString());
                                                num_ILI8818_G16.Value = Decimal.Parse((Rec_tmp[36] & 0x0f).ToString()) * 256 + Decimal.Parse(Rec_tmp[37].ToString());
                                                num_ILI8818_G17.Value = Decimal.Parse((Rec_tmp[38] & 0x0f).ToString()) * 256 + Decimal.Parse(Rec_tmp[39].ToString());
                                                num_ILI8818_G18.Value = Decimal.Parse((Rec_tmp[40] & 0x0f).ToString()) * 256 + Decimal.Parse(Rec_tmp[41].ToString());
                                                num_ILI8818_G19.Value = Decimal.Parse((Rec_tmp[42] & 0x0f).ToString()) * 256 + Decimal.Parse(Rec_tmp[43].ToString());
                                                num_ILI8818_G20.Value = Decimal.Parse((Rec_tmp[44] & 0x0f).ToString()) * 256 + Decimal.Parse(Rec_tmp[45].ToString());
                                                num_ILI8818_G21.Value = Decimal.Parse((Rec_tmp[46] & 0x0f).ToString()) * 256 + Decimal.Parse(Rec_tmp[47].ToString());
                                                num_ILI8818_G22.Value = Decimal.Parse((Rec_tmp[48] & 0x0f).ToString()) * 256 + Decimal.Parse(Rec_tmp[49].ToString());
                                                num_ILI8818_G23.Value = Decimal.Parse((Rec_tmp[50] & 0x0f).ToString()) * 256 + Decimal.Parse(Rec_tmp[51].ToString());

                                            }
                                            frmHelp.textBox1.Text = frmHelp.textBox1.Text + "绿 Gamma数据\t读 OK！\r\n";
                                        }
                                        else if (Setting.TempRecord.ILI8818_GammaCmdType == 0x05)//Blue Register
                                        {

                                            {
                                                num_ILI8818_B0.Value = Decimal.Parse((Rec_tmp[4] & 0x0f).ToString()) * 256 + Decimal.Parse(Rec_tmp[5].ToString());
                                                num_ILI8818_B1.Value = Decimal.Parse((Rec_tmp[6] & 0x0f).ToString()) * 256 + Decimal.Parse(Rec_tmp[7].ToString());
                                                num_ILI8818_B2.Value = Decimal.Parse((Rec_tmp[8] & 0x0f).ToString()) * 256 + Decimal.Parse(Rec_tmp[9].ToString());
                                                num_ILI8818_B3.Value = Decimal.Parse((Rec_tmp[10] & 0x0f).ToString()) * 256 + Decimal.Parse(Rec_tmp[11].ToString());
                                                num_ILI8818_B4.Value = Decimal.Parse((Rec_tmp[12] & 0x0f).ToString()) * 256 + Decimal.Parse(Rec_tmp[13].ToString());
                                                num_ILI8818_B5.Value = Decimal.Parse((Rec_tmp[14] & 0x0f).ToString()) * 256 + Decimal.Parse(Rec_tmp[15].ToString());
                                                num_ILI8818_B6.Value = Decimal.Parse((Rec_tmp[16] & 0x0f).ToString()) * 256 + Decimal.Parse(Rec_tmp[17].ToString());
                                                num_ILI8818_B7.Value = Decimal.Parse((Rec_tmp[18] & 0x0f).ToString()) * 256 + Decimal.Parse(Rec_tmp[19].ToString());
                                                num_ILI8818_B8.Value = Decimal.Parse((Rec_tmp[20] & 0x0f).ToString()) * 256 + Decimal.Parse(Rec_tmp[21].ToString());
                                                num_ILI8818_B9.Value = Decimal.Parse((Rec_tmp[22] & 0x0f).ToString()) * 256 + Decimal.Parse(Rec_tmp[23].ToString());
                                                num_ILI8818_B10.Value = Decimal.Parse((Rec_tmp[24] & 0x0f).ToString()) * 256 + Decimal.Parse(Rec_tmp[25].ToString());
                                                num_ILI8818_B11.Value = Decimal.Parse((Rec_tmp[26] & 0x0f).ToString()) * 256 + Decimal.Parse(Rec_tmp[27].ToString());

                                                num_ILI8818_B12.Value = Decimal.Parse((Rec_tmp[28] & 0x0f).ToString()) * 256 + Decimal.Parse(Rec_tmp[29].ToString());
                                                num_ILI8818_B13.Value = Decimal.Parse((Rec_tmp[30] & 0x0f).ToString()) * 256 + Decimal.Parse(Rec_tmp[31].ToString());
                                                num_ILI8818_B14.Value = Decimal.Parse((Rec_tmp[32] & 0x0f).ToString()) * 256 + Decimal.Parse(Rec_tmp[33].ToString());
                                                num_ILI8818_B15.Value = Decimal.Parse((Rec_tmp[34] & 0x0f).ToString()) * 256 + Decimal.Parse(Rec_tmp[35].ToString());
                                                num_ILI8818_B16.Value = Decimal.Parse((Rec_tmp[36] & 0x0f).ToString()) * 256 + Decimal.Parse(Rec_tmp[37].ToString());
                                                num_ILI8818_B17.Value = Decimal.Parse((Rec_tmp[38] & 0x0f).ToString()) * 256 + Decimal.Parse(Rec_tmp[39].ToString());
                                                num_ILI8818_B18.Value = Decimal.Parse((Rec_tmp[40] & 0x0f).ToString()) * 256 + Decimal.Parse(Rec_tmp[41].ToString());
                                                num_ILI8818_B19.Value = Decimal.Parse((Rec_tmp[42] & 0x0f).ToString()) * 256 + Decimal.Parse(Rec_tmp[43].ToString());
                                                num_ILI8818_B20.Value = Decimal.Parse((Rec_tmp[44] & 0x0f).ToString()) * 256 + Decimal.Parse(Rec_tmp[45].ToString());
                                                num_ILI8818_B21.Value = Decimal.Parse((Rec_tmp[46] & 0x0f).ToString()) * 256 + Decimal.Parse(Rec_tmp[47].ToString());
                                                num_ILI8818_B22.Value = Decimal.Parse((Rec_tmp[48] & 0x0f).ToString()) * 256 + Decimal.Parse(Rec_tmp[49].ToString());
                                                num_ILI8818_B23.Value = Decimal.Parse((Rec_tmp[50] & 0x0f).ToString()) * 256 + Decimal.Parse(Rec_tmp[51].ToString());


                                            }
                                            frmHelp.textBox1.Text = frmHelp.textBox1.Text + "蓝 Gamma数据\t读 OK！\r\n";
                                        }
                                    }
                                    break;
                                default: break;
                            }
                        }
                        else if (Rec_tmp[0] == 0x2F)  //Demura
                        {
                            switch (Rec_tmp[1])
                            {
                                case 0x01://Flash ID
                                    {
                                        frmHelp.textBox1.Text = frmHelp.textBox1.Text + "Flash ID: " + Rec_tmp[4].ToString("x") + "," + Rec_tmp[5].ToString("x") + "," + Rec_tmp[6].ToString("x") + "\r\n";
                                    }
                                    break;
                                case 0x02://Flash Setting&De-Mura RAM Enable
                                    {
                                        frmHelp.textBox1.Text = frmHelp.textBox1.Text + "De-Mura RAM Enable.\r\n";
                                    }
                                    break;
                                case 0x03://Data Load
                                    {
                                        frmHelp.textBox1.Text = frmHelp.textBox1.Text + "De-Mura Data Loading ! \r\n";
                                    }
                                    break;
                                case 0x04://De-Mura RAM Disable
                                    {
                                        frmHelp.textBox1.Text = frmHelp.textBox1.Text + "De-Mura RAM Disable" + "\r\n";
                                    }
                                    break;
                                case 0x05://
                                    {
                                        if (Rec_tmp[4] == 0xff)
                                        {
                                            frmHelp.textBox1.Text = frmHelp.textBox1.Text + " Flash Erase Success !\r\n";
                                            MessageBox.Show("擦除完成，请执行下一步。");
                                        }
                                        else
                                        {
                                            frmHelp.textBox1.Text = frmHelp.textBox1.Text + " Flash Erase Failed ! \r\n";
                                            MessageBox.Show("擦除失败，请重试。");
                                        }

                                    }
                                    break;
                                case 0x06://Flash Writing
                                    {
                                        if (Rec_tmp[4] == 0x88)
                                        {
                                            frmHelp.textBox1.Text = frmHelp.textBox1.Text + "De-Mura Data Writing Successful. \r\n";
                                            MessageBox.Show("写入完成，请进行下一步。");
                                        }
                                        else
                                        {
                                            frmHelp.textBox1.Text = frmHelp.textBox1.Text + "Please Re-Write Data. \r\n";
                                            MessageBox.Show("写入失败，请重试。");
                                        }
                                    }
                                    break;
                                case 0x07://Reload
                                    {
                                        frmHelp.textBox1.Text = frmHelp.textBox1.Text + "Re-Load De-Mura Data Sucessful ! " + "\r\n";
                                    }
                                    break;
                                case 0x08://CRC Check
                                    {
                                        frmHelp.textBox1.Text = frmHelp.textBox1.Text + "Re-Load Data CRC: " + Rec_tmp[4].ToString("x") + "," + Rec_tmp[5].ToString("x") + "\r\n" + "Calc CRC: " + Rec_tmp[6].ToString("x") + "," + Rec_tmp[7].ToString("x") + " \r\n";
                                    }
                                    break;
                                case 0x09://De-Mura Function Off
                                    {
                                        frmHelp.textBox1.Text = frmHelp.textBox1.Text + "De-Mura Function On. \r\n";
                                    }
                                    break;
                                case 0x0A://De-Mura Function On
                                    {
                                        frmHelp.textBox1.Text = frmHelp.textBox1.Text + "De-Mura Function Off. \r\n";
                                    }
                                    break;
                                default:
                                    break;
                            }
                        }

                        frmHelp.textBox1.SelectionStart = this.frmHelp.textBox1.Text.Length;
                        frmHelp.textBox1.ScrollToCaret();//滚动到光标处
                        if (frmHelp.textBox1.Lines.Length > 50) frmHelp.textBox1.Text = null;
                    }));
                }
            }
            finally
            {
                Listening = false;
            }
        }
        //Gamma保存
        private void ILI8818_SaveGamma_Click(object sender, EventArgs e)
        {
            SaveFileDialog sf = new SaveFileDialog(); //对话框
            sf.Filter = @"csv文件(*.csv)|*.csv|所有文件(*.*)|*.*"; //定义保存的文件的类型
            string str = "保存Gamma文件";
            sf.FileName = PAGE_comboBox.Text;
            if (sf.ShowDialog() == DialogResult.OK) //如果确定保存
            {
                if (sf.FileName == "") return; //如果没有输入文件名
                try
                {
                    StreamWriter sw = null; //文件流
                    sw = new StreamWriter(sf.FileName, false, Encoding.UTF8);
                    str = str + "R00," + num_ILI8818_R0.Text + "," + "G00," + num_ILI8818_G0.Text + "," + "B00," + num_ILI8818_B0.Text + "\r\n";
                    str = str + "R01," + num_ILI8818_R1.Text + "," + "G01," + num_ILI8818_G1.Text + "," + "B01," + num_ILI8818_B1.Text + "\r\n";
                    str = str + "R03," + num_ILI8818_R2.Text + "," + "G03," + num_ILI8818_G2.Text + "," + "B03," + num_ILI8818_B2.Text + "\r\n";
                    str = str + "R05," + num_ILI8818_R3.Text + "," + "G05," + num_ILI8818_G3.Text + "," + "B05," + num_ILI8818_B3.Text + "\r\n";
                    str = str + "R09," + num_ILI8818_R4.Text + "," + "G09," + num_ILI8818_G4.Text + "," + "B09," + num_ILI8818_B4.Text + "\r\n";
                    str = str + "R13," + num_ILI8818_R5.Text + "," + "G13," + num_ILI8818_G5.Text + "," + "B13," + num_ILI8818_B5.Text + "\r\n";

                    str = str + "R17," + num_ILI8818_R6.Text + "," + "G17," + num_ILI8818_G6.Text + "," + "B17," + num_ILI8818_B6.Text + "\r\n";
                    str = str + "R22," + num_ILI8818_R7.Text + "," + "G22," + num_ILI8818_G7.Text + "," + "B22," + num_ILI8818_B7.Text + "\r\n";
                    str = str + "R29," + num_ILI8818_R8.Text + "," + "G29," + num_ILI8818_G8.Text + "," + "B29," + num_ILI8818_B8.Text + "\r\n";
                    str = str + "R35," + num_ILI8818_R9.Text + "," + "G35," + num_ILI8818_G9.Text + "," + "B35," + num_ILI8818_B9.Text + "\r\n";
                    str = str + "R41," + num_ILI8818_R10.Text + "," + "G41," + num_ILI8818_G10.Text + "," + "B41," + num_ILI8818_B10.Text + "\r\n";
                    str = str + "R51," + num_ILI8818_R11.Text + "," + "G51," + num_ILI8818_G11.Text + "," + "B51," + num_ILI8818_B11.Text + "\r\n";

                    str = str + "R65," + num_ILI8818_R12.Text + "," + "G65," + num_ILI8818_G12.Text + "," + "B65," + num_ILI8818_B12.Text + "\r\n";
                    str = str + "R81," + num_ILI8818_R13.Text + "," + "G81," + num_ILI8818_G13.Text + "," + "B81," + num_ILI8818_B13.Text + "\r\n";
                    str = str + "R93," + num_ILI8818_R14.Text + "," + "G93," + num_ILI8818_G14.Text + "," + "B93," + num_ILI8818_B14.Text + "\r\n";
                    str = str + "R104," + num_ILI8818_R15.Text + "," + "G104," + num_ILI8818_G15.Text + "," + "B104," + num_ILI8818_B15.Text + "\r\n";
                    str = str + "R114," + num_ILI8818_R16.Text + "," + "G114," + num_ILI8818_G16.Text + "," + "B114," + num_ILI8818_B16.Text + "\r\n";
                    str = str + "R134," + num_ILI8818_R17.Text + "," + "G134," + num_ILI8818_G17.Text + "," + "B134," + num_ILI8818_B17.Text + "\r\n";

                    str = str + "R159," + num_ILI8818_R18.Text + "," + "G159," + num_ILI8818_G18.Text + "," + "B159," + num_ILI8818_B18.Text + "\r\n";
                    str = str + "R177," + num_ILI8818_R19.Text + "," + "G177," + num_ILI8818_G19.Text + "," + "B177," + num_ILI8818_B19.Text + "\r\n";
                    str = str + "R198," + num_ILI8818_R20.Text + "," + "G198," + num_ILI8818_G20.Text + "," + "B198," + num_ILI8818_B20.Text + "\r\n";
                    str = str + "R225," + num_ILI8818_R21.Text + "," + "G225," + num_ILI8818_G21.Text + "," + "B225," + num_ILI8818_B21.Text + "\r\n";
                    str = str + "R247," + num_ILI8818_R22.Text + "," + "G247," + num_ILI8818_G22.Text + "," + "B247," + num_ILI8818_B22.Text + "\r\n";
                    str = str + "R225," + num_ILI8818_R23.Text + "," + "G225," + num_ILI8818_G23.Text + "," + "B225," + num_ILI8818_B23.Text + "\r\n";


                    sw.WriteLine(str);
                    sw.Dispose(); //释放资源
                    sw.Close(); //关闭数据流
                    MessageBox.Show("Gamma保存OK！", "系统提示：");
                }
                catch
                {
                    MessageBox.Show("Gamma保存时发生错误，请再试！", "系统提示：");
                }
            }
        } //
        //Gamma载入
        private void ILI8818_LoadGamma_Click(object sender, EventArgs e)
        {
            OpenFileDialog of = new OpenFileDialog();
            string strtmp = "";
            of.Filter = @"csv文件(*.csv)|*.csv|所有文件(*.*)|*.*"; ;
            of.Title = "打开Gamma文件";

            if (of.ShowDialog() == DialogResult.OK)
            {
                //读取文本信息
                FileStream fs = new FileStream(of.FileName, FileMode.Open, FileAccess.Read);
                StreamReader streamReader = new StreamReader(fs, Encoding.GetEncoding("GBK"));
                streamReader.BaseStream.Seek(0, SeekOrigin.Begin);
                string strLine = streamReader.ReadLine();
                //循环读取文本信息
                while (!string.IsNullOrEmpty(strLine))
                {
                    strtmp = strtmp + strLine + ",";
                    strLine = streamReader.ReadLine(); //循环读取下一行
                }
                fs.Close(); //关闭流
                streamReader.Close();
                string[] arrtmp = strtmp.Split(new Char[] { ',' });
                num_ILI8818_R0.Text = arrtmp[1].ToString(); num_ILI8818_G0.Text = arrtmp[3].ToString(); num_ILI8818_B0.Text = arrtmp[5].ToString();
                num_ILI8818_R1.Text = arrtmp[7].ToString(); num_ILI8818_G1.Text = arrtmp[9].ToString(); num_ILI8818_B1.Text = arrtmp[11].ToString();
                num_ILI8818_R2.Text = arrtmp[13].ToString(); num_ILI8818_G2.Text = arrtmp[15].ToString(); num_ILI8818_B2.Text = arrtmp[17].ToString();
                num_ILI8818_R3.Text = arrtmp[19].ToString(); num_ILI8818_G3.Text = arrtmp[21].ToString(); num_ILI8818_B3.Text = arrtmp[23].ToString();
                num_ILI8818_R4.Text = arrtmp[25].ToString(); num_ILI8818_G4.Text = arrtmp[27].ToString(); num_ILI8818_B4.Text = arrtmp[29].ToString();
                num_ILI8818_R5.Text = arrtmp[31].ToString(); num_ILI8818_G5.Text = arrtmp[33].ToString(); num_ILI8818_B5.Text = arrtmp[35].ToString();

                num_ILI8818_R6.Text = arrtmp[37].ToString(); num_ILI8818_G6.Text = arrtmp[39].ToString(); num_ILI8818_B6.Text = arrtmp[41].ToString();
                num_ILI8818_R7.Text = arrtmp[43].ToString(); num_ILI8818_G7.Text = arrtmp[45].ToString(); num_ILI8818_B7.Text = arrtmp[47].ToString();
                num_ILI8818_R8.Text = arrtmp[49].ToString(); num_ILI8818_G8.Text = arrtmp[51].ToString(); num_ILI8818_B8.Text = arrtmp[53].ToString();
                num_ILI8818_R9.Text = arrtmp[55].ToString(); num_ILI8818_G9.Text = arrtmp[57].ToString(); num_ILI8818_B9.Text = arrtmp[59].ToString();
                num_ILI8818_R10.Text = arrtmp[61].ToString(); num_ILI8818_G10.Text = arrtmp[63].ToString(); num_ILI8818_B10.Text = arrtmp[65].ToString();
                num_ILI8818_R11.Text = arrtmp[67].ToString(); num_ILI8818_G11.Text = arrtmp[69].ToString(); num_ILI8818_B11.Text = arrtmp[71].ToString();

                num_ILI8818_R12.Text = arrtmp[73].ToString(); num_ILI8818_G12.Text = arrtmp[75].ToString(); num_ILI8818_B12.Text = arrtmp[77].ToString();
                num_ILI8818_R13.Text = arrtmp[79].ToString(); num_ILI8818_G13.Text = arrtmp[81].ToString(); num_ILI8818_B13.Text = arrtmp[83].ToString();
                num_ILI8818_R14.Text = arrtmp[85].ToString(); num_ILI8818_G14.Text = arrtmp[87].ToString(); num_ILI8818_B14.Text = arrtmp[89].ToString();
                num_ILI8818_R15.Text = arrtmp[91].ToString(); num_ILI8818_G15.Text = arrtmp[93].ToString(); num_ILI8818_B15.Text = arrtmp[95].ToString();
                num_ILI8818_R16.Text = arrtmp[97].ToString(); num_ILI8818_G16.Text = arrtmp[99].ToString(); num_ILI8818_B16.Text = arrtmp[101].ToString();
                num_ILI8818_R17.Text = arrtmp[103].ToString(); num_ILI8818_G17.Text = arrtmp[105].ToString(); num_ILI8818_B17.Text = arrtmp[107].ToString();

                num_ILI8818_R18.Text = arrtmp[109].ToString(); num_ILI8818_G18.Text = arrtmp[111].ToString(); num_ILI8818_B18.Text = arrtmp[113].ToString();
                num_ILI8818_R19.Text = arrtmp[115].ToString(); num_ILI8818_G19.Text = arrtmp[117].ToString(); num_ILI8818_B19.Text = arrtmp[119].ToString();
                num_ILI8818_R20.Text = arrtmp[121].ToString(); num_ILI8818_G20.Text = arrtmp[123].ToString(); num_ILI8818_B20.Text = arrtmp[125].ToString();
                num_ILI8818_R21.Text = arrtmp[127].ToString(); num_ILI8818_G21.Text = arrtmp[129].ToString(); num_ILI8818_B21.Text = arrtmp[131].ToString();
                num_ILI8818_R22.Text = arrtmp[133].ToString(); num_ILI8818_G22.Text = arrtmp[135].ToString(); num_ILI8818_B22.Text = arrtmp[137].ToString();
                num_ILI8818_R23.Text = arrtmp[139].ToString(); num_ILI8818_G23.Text = arrtmp[141].ToString(); num_ILI8818_B23.Text = arrtmp[143].ToString();

            }
        }
        //Gamma2.2目标值计算
        private void btn_ILI8818_Calculate_Click(object sender, EventArgs e)
        {
            double Lr_d, Lg_d, Lb_d;

            string[] arr = ILI8818_Gamma_SetBox.Lines;
            {
                try
                {
                    Diven_Gamma.Clear();
                    Diven_Offset.Clear();
                    for (int i = 0; i < arr.Length; i++)
                    {
                        string line = arr[i];
                        line = line.Replace(" ", "");
                        if (line.Contains("TUNING_SPEC"))
                        {
                            line = line.Replace("TUNING_SPEC", "");
                            line = line.Replace("(", "");
                            line = line.Replace(")", "");
                            string[] arr0 = line.Split(',');
                            Setting.Gamma_Property Gamma = new Setting.Gamma_Property(Convert.ToInt32(arr0[0]), Convert.ToInt32(arr0[1]), Convert.ToDouble(arr0[2]), Convert.ToDouble(arr0[3]), Convert.ToDouble(arr0[4]));
                            Diven_Gamma.Add(Gamma);
                        }
                        else if (line.Contains("LXY_SPEC"))
                        {
                            line = line.Replace("LXY_SPEC", "");
                            line = line.Replace("(", "");
                            line = line.Replace(")", "");
                            string[] arr1 = line.Split(',');
                            //将Offset对象放入集合
                            Setting.Offset_Property Offset = new Setting.Offset_Property(Convert.ToInt32(arr1[0]), Convert.ToDouble(arr1[1]), Convert.ToDouble(arr1[2]), Convert.ToDouble(arr1[3]));
                            Diven_Offset.Add(Offset);
                        }
                    }
                }
                catch
                {
                    MessageBox.Show("格式输入有误");
                }
            }
            //----------------------------------------------------------------------------
            try
            {
                txt_ILI8818_loff.Text = Diven_Offset[0].LUM_OFF.ToString();
                txt_ILI8818_xoff.Text = Diven_Offset[0].X_OFF.ToString();
                txt_ILI8818_yoff.Text = Diven_Offset[0].Y_OFF.ToString();

                int Total_points = Diven_Gamma[0].Points_num;
                D_lums = new double[Total_points, 3];
                D_lum = new double[Total_points];
                txt_ILI8818_gamma.Text = Diven_Gamma[0].Curve.ToString();
                txt_ILI8818_lum.Text = Diven_Gamma[0].Lum.ToString();
                txt_ILI8818_x.Text = Diven_Gamma[0].X.ToString();
                txt_ILI8818_y.Text = Diven_Gamma[0].Y.ToString();
                Points_LV.Text = "";
                for (int p = 0; p < Total_points; p++)
                {
                    D_lum[p] = (Math.Pow((Diven_Offset[p].NO / 255.0), Diven_Gamma[0].Curve) * Diven_Gamma[0].Lum); //每绑点目标亮度
                    Points_LV.Text = Points_LV.Text + Diven_Offset[p].NO + ":  " + Math.Round(D_lum[p], 6) + "\r\n";
                }

                CaSDKObj.YUV_to_RGB(Diven_Gamma[0].Y, Diven_Gamma[0].X, out Lr_d, out Lb_d, out Lg_d);//R/B/G分亮度转换

                for (int i = 0; i < Total_points; i++)
                {
                    D_lums[i, 0] = D_lum[i] * Lr_d; //R/B/G分亮度计算
                    D_lums[i, 1] = D_lum[i] * Lg_d;
                    D_lums[i, 2] = D_lum[i] * Lb_d;
                }
            }
            catch
            {
                MessageBox.Show("格式输入有误");
            }
        }
        //自动调节启动开关
        private void btn_ILI8818_AutoGammas_Click(object sender, EventArgs e)
        {
            index = 0;
            flag1 = 1;
            flag2 = 1;
            flag3 = 1;
            gamma_r = GAMMAs.ILI8818_Gamma_r;
            gamma_g = GAMMAs.ILI8818_Gamma_g;
            gamma_b = GAMMAs.ILI8818_Gamma_b;


            Application.DoEvents();
            if (!chkBISTMode.Checked)
            {
                frmHelp.OLED_Show_Click(frmHelp.btnwhite, e);
                frmHelp.numPatternR.Value = 255;
                frmHelp.numPatternG.Value = 255;
                frmHelp.numPatternB.Value = 255;
                frmHelp.OLED_Show_Click(frmHelp.btnPatternW, e);
            }
            else  //best 模式
            {
                numPatternR.Value = 255;
                numPatternG.Value = 255;
                numPatternB.Value = 255;
                btnBISTGrayShow_Click(sender, e);
            }

            ILI8818_GammaWR_Click(btn_ILI8818_GammaW_RED, e);
            ILI8818_GammaWR_Click(btn_ILI8818_GammaW_GREEN, e);
            ILI8818_GammaWR_Click(btn_ILI8818_GammaW_BLUE, e);

            txt_Reg_Data_WR.Text = "FF,78,38,0C";
            ILI8818_Others_Click(btn_Reg_W, e);
            Thread.Sleep(100); //毫秒
            txt_Reg_Data_WR.Text = "E3,01";  //解锁
            ILI8818_Others_Click(btn_Reg_W, e);
            Thread.Sleep(100); //毫秒
            if (rbt_ILI8818_Normal_1.Checked == true) { txt_Reg_Data_WR.Text = "FF,78,38,20"; ILI8818_Others_Click(btn_Reg_W, e); }
            //else if (rbt_ILI8818_Normal_2.Checked == true) {  txt_Reg_Data_WR.Text = "FF,78,38,0A"; }
            //else if (rbt_ILI8818_Normal_3.Checked == true) {  txt_Reg_Data_WR.Text = "FF,78,38,0B"; }
            //else if (rbt_ILI8818_Normal_4.Checked == true) {  txt_Reg_Data_WR.Text = "FF,78,38,0C"; }
            else if (rbt_ILI8818_HBM.Checked == true) { txt_Reg_Data_WR.Text = "FF,78,38,1E"; ILI8818_Others_Click(btn_Reg_W, e); }//E
            else if (rbt_ILI8818_AOD.Checked == true) { txt_Reg_Data_WR.Text = "FF,78,38,2B"; ILI8818_Others_Click(btn_Reg_W, e); }//F
            else if (rbt_ILI8818_zidingyi.Checked == true) { ILI8818_GammaWR_Click(btn_ILI8818_GammaW_RED, e); }
            btn_ILI8818_Calculate_Click(null, null);

            Thread.Sleep(10);
            T20.Enabled = true;

        }
        //自动调节关闭开关  
        private void btn_ILI8818_Stop_Click(object sender, EventArgs e)
        {
            T20.Enabled = false;
            flag1 = 1;
            flag2 = 1;
            flag3 = 1;
        }
        private void Reg_E3_locked(int en, EventArgs e)
        {
            txt_Reg_Data_WR.Text = "FF,78,38,0C";
            ILI8818_Others_Click(btn_Reg_W, e);
            //Thread.Sleep(2); //毫秒
            if (en == 1)
            {
                txt_Reg_Data_WR.Text = "E3,01";  //解锁
            }
            else
            {
                txt_Reg_Data_WR.Text = "E3,00";  //上锁
            }
            ILI8818_Others_Click(btn_Reg_W, e);
            // Thread.Sleep(2); //毫秒
            if (rbt_ILI8818_Normal_1.Checked == true) { txt_Reg_Data_WR.Text = "FF,78,38,20"; ILI8818_Others_Click(btn_Reg_W, e); }
            //else if (rbt_ILI8818_Normal_2.Checked == true) {  txt_Reg_Data_WR.Text = "FF,78,38,0A"; }
            //else if (rbt_ILI8818_Normal_3.Checked == true) {  txt_Reg_Data_WR.Text = "FF,78,38,0B"; }
            //else if (rbt_ILI8818_Normal_4.Checked == true) {  txt_Reg_Data_WR.Text = "FF,78,38,0C"; }
            else if (rbt_ILI8818_HBM.Checked == true) { txt_Reg_Data_WR.Text = "FF,78,38,1E"; ILI8818_Others_Click(btn_Reg_W, e); }//E
            else if (rbt_ILI8818_AOD.Checked == true) { txt_Reg_Data_WR.Text = "FF,78,38,2B"; ILI8818_Others_Click(btn_Reg_W, e); }//F
            else if (rbt_ILI8818_zidingyi.Checked == true) { ILI8818_GammaWR_Click(btn_ILI8818_GammaW_RED, e); }
        }
        private void T20_Tick(object sender, EventArgs e)
        {
            T20.Stop();
            ILI8818_Gamma_Tuning(null, null);
            T20.Start();
        }

        private void 保存gamma绑点配置ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (ILI8818_Gamma_SetBox.Text == string.Empty)
            {
                MessageBox.Show("内容为空!");
            }
            else
            {
                //创建保存对话框对象
                SaveFileDialog save = new SaveFileDialog();
                save.Filter = "Code files (*.txt)|*.txt"; //过滤文件类型
                save.FilterIndex = 1;
                save.RestoreDirectory = true;
                if (save.ShowDialog() == DialogResult.OK)
                {
                    string path = save.FileName;
                    save.DefaultExt = ".txt";
                    StreamWriter sw = new StreamWriter(path);
                    sw.WriteLine(ILI8818_Gamma_SetBox.Text);
                    sw.Close();
                }
            }
        }

        private void 载入gamma绑点配置ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            OpenFileDialog of = new OpenFileDialog();
            of.Filter = "文本文件(*.txt)|*.txt|所有文件(*.*)|*.*";
            of.Title = "载入ILI8818 gamma绑点";

            if (of.ShowDialog() == DialogResult.OK)
            {
                ILI8818_Gamma_SetBox.Clear();
                //读取文本信息
                FileStream fs = new FileStream(of.FileName, FileMode.Open, FileAccess.Read);
                StreamReader streamReader = new StreamReader(fs, Encoding.GetEncoding("GBK"));
                streamReader.BaseStream.Seek(0, SeekOrigin.Begin);
                string str_generate = streamReader.ReadLine();
                //循环读取文本信息
                while (!string.IsNullOrEmpty(str_generate))
                {
                    ILI8818_Gamma_SetBox.AppendText(str_generate + "\r\n");
                    str_generate = streamReader.ReadLine(); //循环读取下一行
                }
                fs.Close(); //关闭流
                streamReader.Close();
            }
        }

        private void The_custom_GammaWR_Click(object sender, EventArgs e)
        {
            Button btnTmp = (Button)sender;
            switch (btnTmp.Name)
            {
                case "btn_ILI8818_GammaW_RED":
                    {
                        if (rbt_ILI8818_zidingyi.Checked == true)
                        {
                            Send_Cmd_Click(btnSend6_W, e);
                            //Thread.Sleep(0); //毫秒
                        }
                    }
                    break;
                case "btn_ILI8818_GammaW_GREEN":
                    {
                        if (rbt_ILI8818_zidingyi.Checked == true)
                        {
                            Send_Cmd_Click(btnSend6_W, e);
                            //Thread.Sleep(100); //毫秒
                        }

                    }
                    break;
                case "btn_ILI8818_GammaW_BLUE":
                    {
                        if (rbt_ILI8818_zidingyi.Checked == true)
                        {
                            Send_Cmd_Click(btnSend6_W, e);
                            //Thread.Sleep(100); //毫秒
                        }
                    }
                    break;
                //-----------------------------------------------------------------------
                case "btn_ILI8818_GammaR_RED":// 0x6F,0x09,0x49,0x10
                    {
                        if (rbt_ILI8818_zidingyi.Checked == true)
                        {
                            Send_Cmd_Click(btnSend7_R, e);
                            //Thread.Sleep(100); //毫秒
                        }
                    }
                    break;
                case "btn_ILI8818_GammaR_GREEN":
                    {
                        if (rbt_ILI8818_zidingyi.Checked == true)
                        {
                            Send_Cmd_Click(btnSend7_R, e);
                            //Thread.Sleep(100); //毫秒
                        }
                    }
                    break;
                case "btn_ILI8818_GammaR_BLUE":
                    {
                        if (rbt_ILI8818_zidingyi.Checked == true)
                        {
                            Send_Cmd_Click(btnSend7_R, e);
                            //Thread.Sleep(100); //毫秒
                        }
                    }
                    break;
            }
        }
        private void ILI8818_GammaWR_Click(object sender, EventArgs e)
        {
            The_custom_GammaWR_Click(sender, e);
            Button btnTmp = (Button)sender;
            Send_buf = new byte[54];
            Setting.TempRecord.cmdLen = 54;//
            Send_buf[0] = 0x6F; //ILI8818
            Send_buf[2] = 49;//0x31  CRC校验-2，-1了
            //----------Gamma段切换-------------
            if (rbt_ILI8818_Normal_1.Checked == true) { Send_buf[3] = 0x00; txt_Reg_Data_WR.Text = "FF,78,38,20"; }
            //else if (rbt_ILI8818_Normal_2.Checked == true) { Send_buf[3] = 0x01; txt_Reg_Data_WR.Text = "FF,78,38,0A"; }
            //else if (rbt_ILI8818_Normal_3.Checked == true) { Send_buf[3] = 0x02; txt_Reg_Data_WR.Text = "FF,78,38,0B"; }
            //else if (rbt_ILI8818_Normal_4.Checked == true) { Send_buf[3] = 0x03; txt_Reg_Data_WR.Text = "FF,78,38,0C"; }
            else if (rbt_ILI8818_HBM.Checked == true)
            {
                Send_buf[3] = 0x04; txt_Reg_Data_WR.Text = "FF,78,38,1E";
            }//E
            else if (rbt_ILI8818_AOD.Checked == true) { Send_buf[3] = 0x05; txt_Reg_Data_WR.Text = "FF,78,38,2B"; }//F
            else if (rbt_ILI8818_zidingyi.Checked == true) { Send_buf[3] = 0x0f; }
            //----------------------------------------------------------------------------------
            switch (btnTmp.Name)
            {
                case "btn_ILI8818_GammaW_RED":
                    {
                        Send_buf[1] = 0x08;
                        Send_buf[3] |= 0x10; //RED
                        //Send_buf[2] = 48;//24*2=49
                        {
                            Send_buf[4] = Convert.ToByte(Convert.ToUInt16(num_ILI8818_R0.Value.ToString()) >> 8);
                            Send_buf[5] = Convert.ToByte((Convert.ToUInt16(num_ILI8818_R0.Value.ToString())) & 0xff);
                            Send_buf[6] = Convert.ToByte(Convert.ToUInt16(num_ILI8818_R1.Value.ToString()) >> 8);
                            Send_buf[7] = Convert.ToByte((Convert.ToUInt16(num_ILI8818_R1.Value.ToString())) & 0xff);
                            Send_buf[8] = Convert.ToByte(Convert.ToUInt16(num_ILI8818_R2.Value.ToString()) >> 8);
                            Send_buf[9] = Convert.ToByte((Convert.ToUInt16(num_ILI8818_R2.Value.ToString())) & 0xff);
                            Send_buf[10] = Convert.ToByte(Convert.ToUInt16(num_ILI8818_R3.Value.ToString()) >> 8);
                            Send_buf[11] = Convert.ToByte((Convert.ToUInt16(num_ILI8818_R3.Value.ToString())) & 0xff);
                            Send_buf[12] = Convert.ToByte(Convert.ToUInt16(num_ILI8818_R4.Value.ToString()) >> 8);
                            Send_buf[13] = Convert.ToByte((Convert.ToUInt16(num_ILI8818_R4.Value.ToString())) & 0xff);
                            Send_buf[14] = Convert.ToByte(Convert.ToUInt16(num_ILI8818_R5.Value.ToString()) >> 8);
                            Send_buf[15] = Convert.ToByte((Convert.ToUInt16(num_ILI8818_R5.Value.ToString())) & 0xff);
                            Send_buf[16] = Convert.ToByte(Convert.ToUInt16(num_ILI8818_R6.Value.ToString()) >> 8);
                            Send_buf[17] = Convert.ToByte((Convert.ToUInt16(num_ILI8818_R6.Value.ToString())) & 0xff);
                            Send_buf[18] = Convert.ToByte(Convert.ToUInt16(num_ILI8818_R7.Value.ToString()) >> 8);
                            Send_buf[19] = Convert.ToByte((Convert.ToUInt16(num_ILI8818_R7.Value.ToString())) & 0xff);
                            Send_buf[20] = Convert.ToByte(Convert.ToUInt16(num_ILI8818_R8.Value.ToString()) >> 8);
                            Send_buf[21] = Convert.ToByte((Convert.ToUInt16(num_ILI8818_R8.Value.ToString())) & 0xff);
                            Send_buf[22] = Convert.ToByte(Convert.ToUInt16(num_ILI8818_R9.Value.ToString()) >> 8);
                            Send_buf[23] = Convert.ToByte((Convert.ToUInt16(num_ILI8818_R9.Value.ToString())) & 0xff);
                            Send_buf[24] = Convert.ToByte(Convert.ToUInt16(num_ILI8818_R10.Value.ToString()) >> 8);
                            Send_buf[25] = Convert.ToByte((Convert.ToUInt16(num_ILI8818_R10.Value.ToString())) & 0xff);
                            Send_buf[26] = Convert.ToByte(Convert.ToUInt16(num_ILI8818_R11.Value.ToString()) >> 8);
                            Send_buf[27] = Convert.ToByte((Convert.ToUInt16(num_ILI8818_R11.Value.ToString())) & 0xff);
                            Send_buf[28] = Convert.ToByte(Convert.ToUInt16(num_ILI8818_R12.Value.ToString()) >> 8);
                            Send_buf[29] = Convert.ToByte((Convert.ToUInt16(num_ILI8818_R12.Value.ToString())) & 0xff);
                            Send_buf[30] = Convert.ToByte(Convert.ToUInt16(num_ILI8818_R13.Value.ToString()) >> 8);
                            Send_buf[31] = Convert.ToByte((Convert.ToUInt16(num_ILI8818_R13.Value.ToString())) & 0xff);
                            Send_buf[32] = Convert.ToByte(Convert.ToUInt16(num_ILI8818_R14.Value.ToString()) >> 8);
                            Send_buf[33] = Convert.ToByte((Convert.ToUInt16(num_ILI8818_R14.Value.ToString())) & 0xff);
                            Send_buf[34] = Convert.ToByte(Convert.ToUInt16(num_ILI8818_R15.Value.ToString()) >> 8);
                            Send_buf[35] = Convert.ToByte((Convert.ToUInt16(num_ILI8818_R15.Value.ToString())) & 0xff);
                            Send_buf[36] = Convert.ToByte(Convert.ToUInt16(num_ILI8818_R16.Value.ToString()) >> 8);
                            Send_buf[37] = Convert.ToByte((Convert.ToUInt16(num_ILI8818_R16.Value.ToString())) & 0xff);
                            Send_buf[38] = Convert.ToByte(Convert.ToUInt16(num_ILI8818_R17.Value.ToString()) >> 8);
                            Send_buf[39] = Convert.ToByte((Convert.ToUInt16(num_ILI8818_R17.Value.ToString())) & 0xff);
                            Send_buf[40] = Convert.ToByte(Convert.ToUInt16(num_ILI8818_R18.Value.ToString()) >> 8);
                            Send_buf[41] = Convert.ToByte((Convert.ToUInt16(num_ILI8818_R18.Value.ToString())) & 0xff);
                            Send_buf[42] = Convert.ToByte(Convert.ToUInt16(num_ILI8818_R19.Value.ToString()) >> 8);
                            Send_buf[43] = Convert.ToByte((Convert.ToUInt16(num_ILI8818_R19.Value.ToString())) & 0xff);
                            Send_buf[44] = Convert.ToByte(Convert.ToUInt16(num_ILI8818_R20.Value.ToString()) >> 8);
                            Send_buf[45] = Convert.ToByte((Convert.ToUInt16(num_ILI8818_R20.Value.ToString())) & 0xff);
                            Send_buf[46] = Convert.ToByte(Convert.ToUInt16(num_ILI8818_R21.Value.ToString()) >> 8);
                            Send_buf[47] = Convert.ToByte((Convert.ToUInt16(num_ILI8818_R21.Value.ToString())) & 0xff);
                            Send_buf[48] = Convert.ToByte(Convert.ToUInt16(num_ILI8818_R22.Value.ToString()) >> 8);
                            Send_buf[49] = Convert.ToByte((Convert.ToUInt16(num_ILI8818_R22.Value.ToString())) & 0xff);
                            Send_buf[50] = Convert.ToByte(Convert.ToUInt16(num_ILI8818_R23.Value.ToString()) >> 8);
                            Send_buf[51] = Convert.ToByte((Convert.ToUInt16(num_ILI8818_R23.Value.ToString())) & 0xff);
                        }
                    }
                    break;
                case "btn_ILI8818_GammaW_GREEN":
                    {
                        Send_buf[1] = 0x08;
                        Send_buf[3] |= 0x20; //GREEN
                        //Send_buf[2] = 48;                        
                        {
                            Send_buf[4] = Convert.ToByte(Convert.ToUInt16(num_ILI8818_G0.Value.ToString()) >> 8);
                            Send_buf[5] = Convert.ToByte((Convert.ToUInt16(num_ILI8818_G0.Value.ToString())) & 0xff);
                            Send_buf[6] = Convert.ToByte(Convert.ToUInt16(num_ILI8818_G1.Value.ToString()) >> 8);
                            Send_buf[7] = Convert.ToByte((Convert.ToUInt16(num_ILI8818_G1.Value.ToString())) & 0xff);
                            Send_buf[8] = Convert.ToByte(Convert.ToUInt16(num_ILI8818_G2.Value.ToString()) >> 8);
                            Send_buf[9] = Convert.ToByte((Convert.ToUInt16(num_ILI8818_G2.Value.ToString())) & 0xff);
                            Send_buf[10] = Convert.ToByte(Convert.ToUInt16(num_ILI8818_G3.Value.ToString()) >> 8);
                            Send_buf[11] = Convert.ToByte((Convert.ToUInt16(num_ILI8818_G3.Value.ToString())) & 0xff);
                            Send_buf[12] = Convert.ToByte(Convert.ToUInt16(num_ILI8818_G4.Value.ToString()) >> 8);
                            Send_buf[13] = Convert.ToByte((Convert.ToUInt16(num_ILI8818_G4.Value.ToString())) & 0xff);
                            Send_buf[14] = Convert.ToByte(Convert.ToUInt16(num_ILI8818_G5.Value.ToString()) >> 8);
                            Send_buf[15] = Convert.ToByte((Convert.ToUInt16(num_ILI8818_G5.Value.ToString())) & 0xff);
                            Send_buf[16] = Convert.ToByte(Convert.ToUInt16(num_ILI8818_G6.Value.ToString()) >> 8);
                            Send_buf[17] = Convert.ToByte((Convert.ToUInt16(num_ILI8818_G6.Value.ToString())) & 0xff);
                            Send_buf[18] = Convert.ToByte(Convert.ToUInt16(num_ILI8818_G7.Value.ToString()) >> 8);
                            Send_buf[19] = Convert.ToByte((Convert.ToUInt16(num_ILI8818_G7.Value.ToString())) & 0xff);
                            Send_buf[20] = Convert.ToByte(Convert.ToUInt16(num_ILI8818_G8.Value.ToString()) >> 8);
                            Send_buf[21] = Convert.ToByte((Convert.ToUInt16(num_ILI8818_G8.Value.ToString())) & 0xff);
                            Send_buf[22] = Convert.ToByte(Convert.ToUInt16(num_ILI8818_G9.Value.ToString()) >> 8);
                            Send_buf[23] = Convert.ToByte((Convert.ToUInt16(num_ILI8818_G9.Value.ToString())) & 0xff);
                            Send_buf[24] = Convert.ToByte(Convert.ToUInt16(num_ILI8818_G10.Value.ToString()) >> 8);
                            Send_buf[25] = Convert.ToByte((Convert.ToUInt16(num_ILI8818_G10.Value.ToString())) & 0xff);
                            Send_buf[26] = Convert.ToByte(Convert.ToUInt16(num_ILI8818_G11.Value.ToString()) >> 8);
                            Send_buf[27] = Convert.ToByte((Convert.ToUInt16(num_ILI8818_G11.Value.ToString())) & 0xff);
                            Send_buf[28] = Convert.ToByte(Convert.ToUInt16(num_ILI8818_G12.Value.ToString()) >> 8);
                            Send_buf[29] = Convert.ToByte((Convert.ToUInt16(num_ILI8818_G12.Value.ToString())) & 0xff);
                            Send_buf[30] = Convert.ToByte(Convert.ToUInt16(num_ILI8818_G13.Value.ToString()) >> 8);
                            Send_buf[31] = Convert.ToByte((Convert.ToUInt16(num_ILI8818_G13.Value.ToString())) & 0xff);
                            Send_buf[32] = Convert.ToByte(Convert.ToUInt16(num_ILI8818_G14.Value.ToString()) >> 8);
                            Send_buf[33] = Convert.ToByte((Convert.ToUInt16(num_ILI8818_G14.Value.ToString())) & 0xff);
                            Send_buf[34] = Convert.ToByte(Convert.ToUInt16(num_ILI8818_G15.Value.ToString()) >> 8);
                            Send_buf[35] = Convert.ToByte((Convert.ToUInt16(num_ILI8818_G15.Value.ToString())) & 0xff);
                            Send_buf[36] = Convert.ToByte(Convert.ToUInt16(num_ILI8818_G16.Value.ToString()) >> 8);
                            Send_buf[37] = Convert.ToByte((Convert.ToUInt16(num_ILI8818_G16.Value.ToString())) & 0xff);
                            Send_buf[38] = Convert.ToByte(Convert.ToUInt16(num_ILI8818_G17.Value.ToString()) >> 8);
                            Send_buf[39] = Convert.ToByte((Convert.ToUInt16(num_ILI8818_G17.Value.ToString())) & 0xff);
                            Send_buf[40] = Convert.ToByte(Convert.ToUInt16(num_ILI8818_G18.Value.ToString()) >> 8);
                            Send_buf[41] = Convert.ToByte((Convert.ToUInt16(num_ILI8818_G18.Value.ToString())) & 0xff);
                            Send_buf[42] = Convert.ToByte(Convert.ToUInt16(num_ILI8818_G19.Value.ToString()) >> 8);
                            Send_buf[43] = Convert.ToByte((Convert.ToUInt16(num_ILI8818_G19.Value.ToString())) & 0xff);
                            Send_buf[44] = Convert.ToByte(Convert.ToUInt16(num_ILI8818_G20.Value.ToString()) >> 8);
                            Send_buf[45] = Convert.ToByte((Convert.ToUInt16(num_ILI8818_G20.Value.ToString())) & 0xff);
                            Send_buf[46] = Convert.ToByte(Convert.ToUInt16(num_ILI8818_G21.Value.ToString()) >> 8);
                            Send_buf[47] = Convert.ToByte((Convert.ToUInt16(num_ILI8818_G21.Value.ToString())) & 0xff);
                            Send_buf[48] = Convert.ToByte(Convert.ToUInt16(num_ILI8818_G22.Value.ToString()) >> 8);
                            Send_buf[49] = Convert.ToByte((Convert.ToUInt16(num_ILI8818_G22.Value.ToString())) & 0xff);
                            Send_buf[50] = Convert.ToByte(Convert.ToUInt16(num_ILI8818_G23.Value.ToString()) >> 8);
                            Send_buf[51] = Convert.ToByte((Convert.ToUInt16(num_ILI8818_G23.Value.ToString())) & 0xff);
                        }
                    }
                    break;
                case "btn_ILI8818_GammaW_BLUE":
                    {
                        Send_buf[1] = 0x08;
                        Send_buf[3] |= 0x30; //BLUE
                        //Send_buf[2] = 48;
                        {
                            Send_buf[4] = Convert.ToByte(Convert.ToUInt16(num_ILI8818_B0.Value.ToString()) >> 8);
                            Send_buf[5] = Convert.ToByte((Convert.ToUInt16(num_ILI8818_B0.Value.ToString())) & 0xff);
                            Send_buf[6] = Convert.ToByte(Convert.ToUInt16(num_ILI8818_B1.Value.ToString()) >> 8);
                            Send_buf[7] = Convert.ToByte((Convert.ToUInt16(num_ILI8818_B1.Value.ToString())) & 0xff);
                            Send_buf[8] = Convert.ToByte(Convert.ToUInt16(num_ILI8818_B2.Value.ToString()) >> 8);
                            Send_buf[9] = Convert.ToByte((Convert.ToUInt16(num_ILI8818_B2.Value.ToString())) & 0xff);
                            Send_buf[10] = Convert.ToByte(Convert.ToUInt16(num_ILI8818_B3.Value.ToString()) >> 8);
                            Send_buf[11] = Convert.ToByte((Convert.ToUInt16(num_ILI8818_B3.Value.ToString())) & 0xff);
                            Send_buf[12] = Convert.ToByte(Convert.ToUInt16(num_ILI8818_B4.Value.ToString()) >> 8);
                            Send_buf[13] = Convert.ToByte((Convert.ToUInt16(num_ILI8818_B4.Value.ToString())) & 0xff);
                            Send_buf[14] = Convert.ToByte(Convert.ToUInt16(num_ILI8818_B5.Value.ToString()) >> 8);
                            Send_buf[15] = Convert.ToByte((Convert.ToUInt16(num_ILI8818_B5.Value.ToString())) & 0xff);
                            Send_buf[16] = Convert.ToByte(Convert.ToUInt16(num_ILI8818_B6.Value.ToString()) >> 8);
                            Send_buf[17] = Convert.ToByte((Convert.ToUInt16(num_ILI8818_B6.Value.ToString())) & 0xff);
                            Send_buf[18] = Convert.ToByte(Convert.ToUInt16(num_ILI8818_B7.Value.ToString()) >> 8);
                            Send_buf[19] = Convert.ToByte((Convert.ToUInt16(num_ILI8818_B7.Value.ToString())) & 0xff);
                            Send_buf[20] = Convert.ToByte(Convert.ToUInt16(num_ILI8818_B8.Value.ToString()) >> 8);
                            Send_buf[21] = Convert.ToByte((Convert.ToUInt16(num_ILI8818_B8.Value.ToString())) & 0xff);
                            Send_buf[22] = Convert.ToByte(Convert.ToUInt16(num_ILI8818_B9.Value.ToString()) >> 8);
                            Send_buf[23] = Convert.ToByte((Convert.ToUInt16(num_ILI8818_B9.Value.ToString())) & 0xff);
                            Send_buf[24] = Convert.ToByte(Convert.ToUInt16(num_ILI8818_B10.Value.ToString()) >> 8);
                            Send_buf[25] = Convert.ToByte((Convert.ToUInt16(num_ILI8818_B10.Value.ToString())) & 0xff);
                            Send_buf[26] = Convert.ToByte(Convert.ToUInt16(num_ILI8818_B11.Value.ToString()) >> 8);
                            Send_buf[27] = Convert.ToByte((Convert.ToUInt16(num_ILI8818_B11.Value.ToString())) & 0xff);
                            Send_buf[28] = Convert.ToByte(Convert.ToUInt16(num_ILI8818_B12.Value.ToString()) >> 8);
                            Send_buf[29] = Convert.ToByte((Convert.ToUInt16(num_ILI8818_B12.Value.ToString())) & 0xff);
                            Send_buf[30] = Convert.ToByte(Convert.ToUInt16(num_ILI8818_B13.Value.ToString()) >> 8);
                            Send_buf[31] = Convert.ToByte((Convert.ToUInt16(num_ILI8818_B13.Value.ToString())) & 0xff);
                            Send_buf[32] = Convert.ToByte(Convert.ToUInt16(num_ILI8818_B14.Value.ToString()) >> 8);
                            Send_buf[33] = Convert.ToByte((Convert.ToUInt16(num_ILI8818_B14.Value.ToString())) & 0xff);
                            Send_buf[34] = Convert.ToByte(Convert.ToUInt16(num_ILI8818_B15.Value.ToString()) >> 8);
                            Send_buf[35] = Convert.ToByte((Convert.ToUInt16(num_ILI8818_B15.Value.ToString())) & 0xff);
                            Send_buf[36] = Convert.ToByte(Convert.ToUInt16(num_ILI8818_B16.Value.ToString()) >> 8);
                            Send_buf[37] = Convert.ToByte((Convert.ToUInt16(num_ILI8818_B16.Value.ToString())) & 0xff);
                            Send_buf[38] = Convert.ToByte(Convert.ToUInt16(num_ILI8818_B17.Value.ToString()) >> 8);
                            Send_buf[39] = Convert.ToByte((Convert.ToUInt16(num_ILI8818_B17.Value.ToString())) & 0xff);
                            Send_buf[40] = Convert.ToByte(Convert.ToUInt16(num_ILI8818_B18.Value.ToString()) >> 8);
                            Send_buf[41] = Convert.ToByte((Convert.ToUInt16(num_ILI8818_B18.Value.ToString())) & 0xff);
                            Send_buf[42] = Convert.ToByte(Convert.ToUInt16(num_ILI8818_B19.Value.ToString()) >> 8);
                            Send_buf[43] = Convert.ToByte((Convert.ToUInt16(num_ILI8818_B19.Value.ToString())) & 0xff);
                            Send_buf[44] = Convert.ToByte(Convert.ToUInt16(num_ILI8818_B20.Value.ToString()) >> 8);
                            Send_buf[45] = Convert.ToByte((Convert.ToUInt16(num_ILI8818_B20.Value.ToString())) & 0xff);
                            Send_buf[46] = Convert.ToByte(Convert.ToUInt16(num_ILI8818_B21.Value.ToString()) >> 8);
                            Send_buf[47] = Convert.ToByte((Convert.ToUInt16(num_ILI8818_B21.Value.ToString())) & 0xff);
                            Send_buf[48] = Convert.ToByte(Convert.ToUInt16(num_ILI8818_B22.Value.ToString()) >> 8);
                            Send_buf[49] = Convert.ToByte((Convert.ToUInt16(num_ILI8818_B22.Value.ToString())) & 0xff);
                            Send_buf[50] = Convert.ToByte(Convert.ToUInt16(num_ILI8818_B23.Value.ToString()) >> 8);
                            Send_buf[51] = Convert.ToByte((Convert.ToUInt16(num_ILI8818_B23.Value.ToString())) & 0xff);
                        }
                    }
                    break;
                //-----------------------------------------------------------------------
                case "btn_ILI8818_GammaR_RED":// 0x6F,0x09,0x49,0x10
                    {
                        Setting.TempRecord.ILI8818_GammaCmdType = 0x03;
                        Send_buf[1] = 0x09;
                        Send_buf[3] |= 0x10;
                    }
                    break;
                case "btn_ILI8818_GammaR_GREEN":
                    {
                        Setting.TempRecord.ILI8818_GammaCmdType = 0x04;
                        Send_buf[1] = 0x09;
                        Send_buf[3] |= 0x20;
                    }
                    break;
                case "btn_ILI8818_GammaR_BLUE":
                    {
                        Setting.TempRecord.ILI8818_GammaCmdType = 0x05;
                        Send_buf[1] = 0x09;
                        Send_buf[3] |= 0x30;
                    }
                    break;
            }
            CRCData.CalculateCrc16(Send_buf, out Send_buf[Setting.TempRecord.cmdLen - 2], out Send_buf[Setting.TempRecord.cmdLen - 1]);
            try
            {
                frmHelp.comPort.Write(Send_buf, 0, Setting.TempRecord.cmdLen);   //
            }
            catch
            {
                MessageBox.Show("串口有误，请检查", "错误");
            }
            frmHelp.T1.Enabled = false;
            frmHelp.T1.Interval = 2000;
            frmHelp.T1.Enabled = true;
        }

        private void ILI8818_GammaWR_All_Click(object sender, EventArgs e)
        {
            Button btnTmp = (Button)sender;
            Send_buf = new byte[150];//48*3+3+3=150
            Setting.TempRecord.cmdLen = 150;//
            Send_buf[0] = 0x6F; //ILI8818
            Send_buf[2] = 145;//0x91
                              //----------Gamma段切换-------------
            if (rbt_ILI8818_Normal_1.Checked == true) { Send_buf[3] = 0x00; txt_Reg_Data_WR.Text = "FF,78,38,20"; }
            //else if (rbt_ILI8818_Normal_2.Checked == true) { Send_buf[3] = 0x01; txt_Reg_Data_WR.Text = "FF,78,38,0A";  }
            //else if (rbt_ILI8818_Normal_3.Checked == true) { Send_buf[3] = 0x02; txt_Reg_Data_WR.Text = "FF,78,38,0B";  }
            //else if (rbt_ILI8818_Normal_4.Checked == true) { Send_buf[3] = 0x03; txt_Reg_Data_WR.Text = "FF,78,38,0C";  }
            else if (rbt_ILI8818_HBM.Checked == true) { Send_buf[3] = 0x04; txt_Reg_Data_WR.Text = "FF,78,38,1E"; }//E
            else if (rbt_ILI8818_AOD.Checked == true) { Send_buf[3] = 0x05; txt_Reg_Data_WR.Text = "FF,78,38,2B"; }//F
            //----------------------------------------------------------------------------------
            switch (btnTmp.Name)
            {
                case "btn_ILI8818_Read_AllGam_Reg":
                    {
                        Send_buf[1] = 0x23;//Gamma值全部读出;
                        Send_buf[3] |= 0x10;
                    }
                    break;
                case "btn_ILI8818_Write_AllGam_Reg":
                    {
                        Send_buf[1] = 0x33;//Gamma值全部写入;
                        Send_buf[3] |= 0x20;

                        for (int i = 0; i < 23; i++)
                        {
                            RGBValueSet(value2array, i, 0, 0);
                            RGBValueSet(value2array, i, 1, 0);
                            RGBValueSet(value2array, i, 2, 0);
                        }
                    }
                    break;
            }
            CRCData.CalculateCrc16(Send_buf, out Send_buf[Setting.TempRecord.cmdLen - 2], out Send_buf[Setting.TempRecord.cmdLen - 1]);
            try
            {
                frmHelp.comPort.Write(Send_buf, 0, Setting.TempRecord.cmdLen);   //
            }
            catch
            {
                MessageBox.Show("串口有误，请检查", "错误");
            }
            frmHelp.T1.Enabled = false;
            frmHelp.T1.Interval = 2000;
            frmHelp.T1.Enabled = true;
        }
        private int[] Point_ILI8818 = new int[24] {//---Gamma绑点数据，这里的数据仅供参考---
            255,247, 225, 198,  177, 159, 134, 114, 104, 93, 81, 65, 51, 41, 35, 29, 22, 17, 13, 9, 5, 3,1,0 };
        private static int[,] RGBValue = new int[24, 3];
        bool array2value = false;   //记录值写入窗体控件(记录绑点RGB寄存器值)的标志位
        bool value2array = true;    //窗体控件值保存到记录标志位
        private void RGBValueSet(bool inoutflag, int index, byte rgb, byte extraInfo)    //把窗体控件上Gamma绑点寄存器值保存于数组，便于后续处理
        {
            NumericUpDown[] NUMG = new NumericUpDown[] { num_ILI8818_G23, num_ILI8818_G22, num_ILI8818_G21, num_ILI8818_G20, num_ILI8818_G19, num_ILI8818_G18, num_ILI8818_G17, num_ILI8818_G16, num_ILI8818_G15, num_ILI8818_G14, num_ILI8818_G13, num_ILI8818_G12, num_ILI8818_G11, num_ILI8818_G10, num_ILI8818_G9, num_ILI8818_G8, num_ILI8818_G7, num_ILI8818_G6, num_ILI8818_G5, num_ILI8818_G4, num_ILI8818_G3, num_ILI8818_G2, num_ILI8818_G1, num_ILI8818_G0 };
            NumericUpDown[] NUMR = new NumericUpDown[] { num_ILI8818_R23, num_ILI8818_R22, num_ILI8818_R21, num_ILI8818_R20, num_ILI8818_R19, num_ILI8818_R18, num_ILI8818_R17, num_ILI8818_R16, num_ILI8818_R15, num_ILI8818_R14, num_ILI8818_R13, num_ILI8818_R12, num_ILI8818_R11, num_ILI8818_R10, num_ILI8818_R9, num_ILI8818_R8, num_ILI8818_R7, num_ILI8818_R6, num_ILI8818_R5, num_ILI8818_R4, num_ILI8818_R3, num_ILI8818_R2, num_ILI8818_R1, num_ILI8818_R0 };
            NumericUpDown[] NUMB = new NumericUpDown[] { num_ILI8818_B23, num_ILI8818_B22, num_ILI8818_B21, num_ILI8818_B20, num_ILI8818_B19, num_ILI8818_B18, num_ILI8818_B17, num_ILI8818_B16, num_ILI8818_B15, num_ILI8818_B14, num_ILI8818_B13, num_ILI8818_B12, num_ILI8818_B11, num_ILI8818_B10, num_ILI8818_B9, num_ILI8818_B8, num_ILI8818_B7, num_ILI8818_B6, num_ILI8818_B5, num_ILI8818_B4, num_ILI8818_B3, num_ILI8818_B2, num_ILI8818_B1, num_ILI8818_B0 };
            if (inoutflag)
            {
                switch (rgb)
                {
                    case 0:
                        RGBValue[index, 0] = (int)NUMR[index].Value;
                        break;
                    case 1:
                        RGBValue[index, 1] = (int)NUMG[index].Value;
                        break;
                    case 2:
                        RGBValue[index, 2] = (int)NUMB[index].Value;
                        break;
                }
            }
            else
            {
                switch (rgb)
                {
                    case 0:
                        NUMR[index].Value = RGBValue[index, 0];
                        break;
                    case 1:
                        NUMG[index].Value = RGBValue[index, 1];
                        break;
                    case 2:
                        NUMB[index].Value = RGBValue[index, 2];
                        break;
                }
            }
        }
        private void ILI8818_Gamma_Tuning(Object myObject, EventArgs e)
        {
            int total_points = Diven_Gamma[0].Points_num;
            double Lr_t, Lg_t, Lb_t, lumr, lumg, lumb;

            frmHelp.Msr_CASDK();

            if (Gamma_adjust_timeout_flag == true)//如果是0绑点
            {
                flag1 = 0;
                flag2 = 0;
                flag3 = 0;
            }
            else
            {
                if ((frmHelp.CASDK_LUM < (D_lum[index] + D_lum[index] * Diven_Offset[index].LUM_OFF / 100)) && (frmHelp.CASDK_LUM > (D_lum[index] - D_lum[index] * Diven_Offset[index].LUM_OFF / 100)))//G
                { flag1 = 0; }
                else
                { flag1 = 1; }
                if ((frmHelp.CASDK_x < (Diven_Gamma[0].X + Diven_Offset[index].X_OFF)) && (frmHelp.CASDK_x > (Diven_Gamma[0].X - Diven_Offset[index].X_OFF)) && flag1 == 0)//R
                { flag3 = 0; }
                else
                { flag3 = 1; }
                if ((frmHelp.CASDK_y < (Diven_Gamma[0].Y + Diven_Offset[index].Y_OFF)) && (frmHelp.CASDK_y > (Diven_Gamma[0].Y - Diven_Offset[index].Y_OFF)) && flag1 == 0 && flag3 == 0)//B
                { flag2 = 0; }
                else
                { flag2 = 1; }

            }
            if (flag1 == 0 && flag2 == 0 && flag3 == 0)
            {
                T20.Enabled = false;
                //reset-----
                Gamma_adjust_timeout_flag = false;
                frmHelp.Gamma_auto_adjust_count = 0;
                //--------
                index++;

                if (index == total_points)
                {
                    frmHelp.textBox1.Text = frmHelp.textBox1.Text + "ILI8818 Gamma调试完毕!\r\n";
                }
                if (index < total_points)
                {
                    if (!chkBISTMode.Checked)
                    {
                        frmHelp.numPatternR.Value = Diven_Offset[index].NO;//固定255灰阶
                        frmHelp.numPatternG.Value = Diven_Offset[index].NO;
                        frmHelp.numPatternB.Value = Diven_Offset[index].NO;

                        Application.DoEvents();
                        txt_Reg_Data_WR.Text = "ff,78,38,00";
                        ILI8818_Others_Click(btn_Reg_W, e);

                        frmHelp.OLED_Show_Click(frmHelp.btnPatternW, null);//写入Pattern参数
                    }
                    else  //best 模式
                    {
                        numPatternR.Value = Diven_Offset[index].NO;
                        numPatternG.Value = Diven_Offset[index].NO;
                        numPatternB.Value = Diven_Offset[index].NO;
                        btnBISTGrayShow_Click(1, e);
                        txt_Reg_Data_WR.Text = "ff,78,38,00";
                        ILI8818_Others_Click(btn_Reg_W, e);
                    }
                    Thread.Sleep(10); //1秒=1000毫秒，

                    if (rbt_ILI8818_Normal_1.Checked == true) { txt_Reg_Data_WR.Text = "FF,78,38,20"; ILI8818_Others_Click(btn_Reg_W, e); }
                    //else if (rbt_ILI8818_Normal_2.Checked == true) {  txt_Reg_Data_WR.Text = "FF,78,38,0A"; }
                    //else if (rbt_ILI8818_Normal_3.Checked == true) {  txt_Reg_Data_WR.Text = "FF,78,38,0B"; }
                    //else if (rbt_ILI8818_Normal_4.Checked == true) {  txt_Reg_Data_WR.Text = "FF,78,38,0C"; }
                    else if (rbt_ILI8818_HBM.Checked == true) { txt_Reg_Data_WR.Text = "FF,78,38,1E"; ILI8818_Others_Click(btn_Reg_W, e); }//E
                    else if (rbt_ILI8818_AOD.Checked == true) { txt_Reg_Data_WR.Text = "FF,78,38,2B"; ILI8818_Others_Click(btn_Reg_W, e); }//F
                    else if (rbt_ILI8818_zidingyi.Checked == true) { ILI8818_GammaWR_Click(btn_ILI8818_GammaW_RED, e); }
                    T20.Enabled = true;
                    flag1 = 1;
                    flag2 = 1;
                    flag3 = 1;
                }
            }
            else
            {
                decimal r = 0, g = 0, b = 0;
                CaSDKObj.YUV_to_RGB(frmHelp.CASDK_y, frmHelp.CASDK_x, out Lr_t, out Lb_t, out Lg_t);

                lumr = frmHelp.CASDK_LUM * Lr_t;
                lumg = frmHelp.CASDK_LUM * Lg_t;
                lumb = frmHelp.CASDK_LUM * Lb_t;

                try
                {
                    switch (index)
                    {
                        #region//---风神算法
                        case 23:
                            {
                                //public void Flexible_Gamma_auto_Adujst(
                                //int lum_adjust_enable, int x_adjust_enable, int y_adjust_enable,
                                //double measure_lum, double measure_x, double measure_y,
                                //double target_lum, double target_x, double target_y,
                                //decimal input_reg_red, decimal input_reg_green, decimal input_reg_blue,
                                //int gary_target, int reg_range,
                                ////output
                                //out decimal output_reg_red, out decimal output_reg_green, out decimal output_reg_blue, out bool timeout_flag)

                                Flexible_Gamma_auto_Adujst(flag1, flag3, flag2, lumg, lumr, lumb, D_lums[index, 1], D_lums[index, 0], D_lums[index, 2], num_ILI8818_R0.Value, num_ILI8818_G0.Value, num_ILI8818_B0.Value, Diven_Offset[index].NO, 0xfff, out r, out g, out b, out Gamma_adjust_timeout_flag);
                                if (Gamma_adjust_timeout_flag == true)
                                {
                                    flag1 = 0; flag3 = 0; flag2 = 0;
                                }
                                num_ILI8818_R0.Value = 0;
                                num_ILI8818_G0.Value = 0;
                                num_ILI8818_B0.Value = 0;
                            }
                            break;
                        case 22:
                            {
                                Flexible_Gamma_auto_Adujst(flag1, flag3, flag2, lumg, lumr, lumb, D_lums[index, 1], D_lums[index, 0], D_lums[index, 2], num_ILI8818_R1.Value, num_ILI8818_G1.Value, num_ILI8818_B1.Value, Diven_Offset[index].NO, 0xfff, out r, out g, out b, out Gamma_adjust_timeout_flag);
                                if (Gamma_adjust_timeout_flag == true)
                                {
                                    flag1 = 0; flag3 = 0; flag2 = 0;
                                }
                                num_ILI8818_R1.Value = r;
                                num_ILI8818_G1.Value = g;
                                num_ILI8818_B1.Value = b;
                            }
                            break;

                        case 21:
                            {
                                Flexible_Gamma_auto_Adujst(flag1, flag3, flag2, lumg, lumr, lumb, D_lums[index, 1], D_lums[index, 0], D_lums[index, 2], num_ILI8818_R2.Value, num_ILI8818_G2.Value, num_ILI8818_B2.Value, Diven_Offset[index].NO, 0xfff, out r, out g, out b, out Gamma_adjust_timeout_flag);
                                if (Gamma_adjust_timeout_flag == true)
                                {
                                    flag1 = 0; flag3 = 0; flag2 = 0;
                                }
                                num_ILI8818_R2.Value = r;
                                num_ILI8818_G2.Value = g;
                                num_ILI8818_B2.Value = b;
                            }
                            break;

                        case 20:
                            {
                                Flexible_Gamma_auto_Adujst(flag1, flag3, flag2, lumg, lumr, lumb, D_lums[index, 1], D_lums[index, 0], D_lums[index, 2], num_ILI8818_R3.Value, num_ILI8818_G3.Value, num_ILI8818_B3.Value, Diven_Offset[index].NO, 0xfff, out r, out g, out b, out Gamma_adjust_timeout_flag);
                                if (Gamma_adjust_timeout_flag == true)
                                {
                                    flag1 = 0; flag3 = 0; flag2 = 0;
                                }
                                num_ILI8818_R3.Value = r;
                                num_ILI8818_G3.Value = g;
                                num_ILI8818_B3.Value = b;
                            }
                            break;

                        case 19:
                            {
                                Flexible_Gamma_auto_Adujst(flag1, flag3, flag2, lumg, lumr, lumb, D_lums[index, 1], D_lums[index, 0], D_lums[index, 2], num_ILI8818_R4.Value, num_ILI8818_G4.Value, num_ILI8818_B4.Value, Diven_Offset[index].NO, 0xfff, out r, out g, out b, out Gamma_adjust_timeout_flag);
                                if (Gamma_adjust_timeout_flag == true)
                                {
                                    flag1 = 0; flag3 = 0; flag2 = 0;
                                }
                                num_ILI8818_R4.Value = r;
                                num_ILI8818_G4.Value = g;
                                num_ILI8818_B4.Value = b;
                            }
                            break;

                        case 18:
                            {
                                Flexible_Gamma_auto_Adujst(flag1, flag3, flag2, lumg, lumr, lumb, D_lums[index, 1], D_lums[index, 0], D_lums[index, 2], num_ILI8818_R5.Value, num_ILI8818_G5.Value, num_ILI8818_B5.Value, Diven_Offset[index].NO, 0xfff, out r, out g, out b, out Gamma_adjust_timeout_flag);
                                if (Gamma_adjust_timeout_flag == true)
                                {
                                    flag1 = 0; flag3 = 0; flag2 = 0;
                                }
                                num_ILI8818_R5.Value = r;
                                num_ILI8818_G5.Value = g;
                                num_ILI8818_B5.Value = b;
                            }
                            break;

                        case 17:
                            {
                                Flexible_Gamma_auto_Adujst(flag1, flag3, flag2, lumg, lumr, lumb, D_lums[index, 1], D_lums[index, 0], D_lums[index, 2], num_ILI8818_R6.Value, num_ILI8818_G6.Value, num_ILI8818_B6.Value, Diven_Offset[index].NO, 0xfff, out r, out g, out b, out Gamma_adjust_timeout_flag);
                                if (Gamma_adjust_timeout_flag == true)
                                {
                                    flag1 = 0; flag3 = 0; flag2 = 0;
                                }
                                num_ILI8818_R6.Value = r;
                                num_ILI8818_G6.Value = g;
                                num_ILI8818_B6.Value = b;
                            }
                            break;

                        case 16:
                            {
                                Flexible_Gamma_auto_Adujst(flag1, flag3, flag2, lumg, lumr, lumb, D_lums[index, 1], D_lums[index, 0], D_lums[index, 2], num_ILI8818_R7.Value, num_ILI8818_G7.Value, num_ILI8818_B7.Value, Diven_Offset[index].NO, 0xfff, out r, out g, out b, out Gamma_adjust_timeout_flag);
                                if (Gamma_adjust_timeout_flag == true)
                                {
                                    flag1 = 0; flag3 = 0; flag2 = 0;
                                }
                                num_ILI8818_R7.Value = r;
                                num_ILI8818_G7.Value = g;
                                num_ILI8818_B7.Value = b;
                            }
                            break;

                        case 15:
                            {
                                Flexible_Gamma_auto_Adujst(flag1, flag3, flag2, lumg, lumr, lumb, D_lums[index, 1], D_lums[index, 0], D_lums[index, 2], num_ILI8818_R8.Value, num_ILI8818_G8.Value, num_ILI8818_B8.Value, Diven_Offset[index].NO, 0xfff, out r, out g, out b, out Gamma_adjust_timeout_flag);
                                if (Gamma_adjust_timeout_flag == true)
                                {
                                    flag1 = 0; flag3 = 0; flag2 = 0;
                                }
                                num_ILI8818_R8.Value = r;
                                num_ILI8818_G8.Value = g;
                                num_ILI8818_B8.Value = b;
                            }
                            break;

                        case 14:
                            {
                                Flexible_Gamma_auto_Adujst(flag1, flag3, flag2, lumg, lumr, lumb, D_lums[index, 1], D_lums[index, 0], D_lums[index, 2], num_ILI8818_R9.Value, num_ILI8818_G9.Value, num_ILI8818_B9.Value, Diven_Offset[index].NO, 0xfff, out r, out g, out b, out Gamma_adjust_timeout_flag);
                                if (Gamma_adjust_timeout_flag == true)
                                {
                                    flag1 = 0; flag3 = 0; flag2 = 0;
                                }
                                num_ILI8818_R9.Value = r;
                                num_ILI8818_G9.Value = g;
                                num_ILI8818_B9.Value = b;

                            }
                            break;

                        case 13:
                            {
                                Flexible_Gamma_auto_Adujst(flag1, flag3, flag2, lumg, lumr, lumb, D_lums[index, 1], D_lums[index, 0], D_lums[index, 2], num_ILI8818_R10.Value, num_ILI8818_G10.Value, num_ILI8818_B10.Value, Diven_Offset[index].NO, 0xfff, out r, out g, out b, out Gamma_adjust_timeout_flag);
                                if (Gamma_adjust_timeout_flag == true)
                                {
                                    flag1 = 0; flag3 = 0; flag2 = 0;
                                }
                                num_ILI8818_R10.Value = r;
                                num_ILI8818_G10.Value = g;
                                num_ILI8818_B10.Value = b;

                            }
                            break;

                        case 12:
                            {
                                Flexible_Gamma_auto_Adujst(flag1, flag3, flag2, lumg, lumr, lumb, D_lums[index, 1], D_lums[index, 0], D_lums[index, 2], num_ILI8818_R11.Value, num_ILI8818_G11.Value, num_ILI8818_B11.Value, Diven_Offset[index].NO, 0xfff, out r, out g, out b, out Gamma_adjust_timeout_flag);
                                if (Gamma_adjust_timeout_flag == true)
                                {
                                    flag1 = 0; flag3 = 0; flag2 = 0;
                                }
                                num_ILI8818_R11.Value = r;
                                num_ILI8818_G11.Value = g;
                                num_ILI8818_B11.Value = b;
                            }
                            break;
                        case 11:
                            {
                                Flexible_Gamma_auto_Adujst(flag1, flag3, flag2, lumg, lumr, lumb, D_lums[index, 1], D_lums[index, 0], D_lums[index, 2], num_ILI8818_R12.Value, num_ILI8818_G12.Value, num_ILI8818_B12.Value, Diven_Offset[index].NO, 0xfff, out r, out g, out b, out Gamma_adjust_timeout_flag);
                                if (Gamma_adjust_timeout_flag == true)
                                {
                                    flag1 = 0; flag3 = 0; flag2 = 0;
                                }
                                num_ILI8818_R12.Value = r;
                                num_ILI8818_G12.Value = g;
                                num_ILI8818_B12.Value = b;
                            }
                            break;
                        case 10:
                            {
                                Flexible_Gamma_auto_Adujst(flag1, flag3, flag2, lumg, lumr, lumb, D_lums[index, 1], D_lums[index, 0], D_lums[index, 2], num_ILI8818_R13.Value, num_ILI8818_G13.Value, num_ILI8818_B13.Value, Diven_Offset[index].NO, 0xfff, out r, out g, out b, out Gamma_adjust_timeout_flag);
                                if (Gamma_adjust_timeout_flag == true)
                                {
                                    flag1 = 0; flag3 = 0; flag2 = 0;
                                }
                                num_ILI8818_R13.Value = r;
                                num_ILI8818_G13.Value = g;
                                num_ILI8818_B13.Value = b;
                            }
                            break;
                        case 9:
                            {
                                Flexible_Gamma_auto_Adujst(flag1, flag3, flag2, lumg, lumr, lumb, D_lums[index, 1], D_lums[index, 0], D_lums[index, 2], num_ILI8818_R14.Value, num_ILI8818_G14.Value, num_ILI8818_B14.Value, Diven_Offset[index].NO, 0xfff, out r, out g, out b, out Gamma_adjust_timeout_flag);
                                if (Gamma_adjust_timeout_flag == true)
                                {
                                    flag1 = 0; flag3 = 0; flag2 = 0;
                                }
                                num_ILI8818_R14.Value = r;
                                num_ILI8818_G14.Value = g;
                                num_ILI8818_B14.Value = b;
                            }
                            break;
                        case 8:
                            {
                                Flexible_Gamma_auto_Adujst(flag1, flag3, flag2, lumg, lumr, lumb, D_lums[index, 1], D_lums[index, 0], D_lums[index, 2], num_ILI8818_R15.Value, num_ILI8818_G15.Value, num_ILI8818_B15.Value, Diven_Offset[index].NO, 0xfff, out r, out g, out b, out Gamma_adjust_timeout_flag);
                                if (Gamma_adjust_timeout_flag == true)
                                {
                                    flag1 = 0; flag3 = 0; flag2 = 0;
                                }
                                num_ILI8818_R15.Value = r;
                                num_ILI8818_G15.Value = g;
                                num_ILI8818_B15.Value = b;
                            }
                            break;
                        case 7:
                            {
                                Flexible_Gamma_auto_Adujst(flag1, flag3, flag2, lumg, lumr, lumb, D_lums[index, 1], D_lums[index, 0], D_lums[index, 2], num_ILI8818_R16.Value, num_ILI8818_G16.Value, num_ILI8818_B16.Value, Diven_Offset[index].NO, 0xfff, out r, out g, out b, out Gamma_adjust_timeout_flag);
                                if (Gamma_adjust_timeout_flag == true)
                                {
                                    flag1 = 0; flag3 = 0; flag2 = 0;
                                }
                                num_ILI8818_R16.Value = r;
                                num_ILI8818_G16.Value = g;
                                num_ILI8818_B16.Value = b;
                            }
                            break;
                        case 6:
                            {
                                Flexible_Gamma_auto_Adujst(flag1, flag3, flag2, lumg, lumr, lumb, D_lums[index, 1], D_lums[index, 0], D_lums[index, 2], num_ILI8818_R17.Value, num_ILI8818_G17.Value, num_ILI8818_B17.Value, Diven_Offset[index].NO, 0xfff, out r, out g, out b, out Gamma_adjust_timeout_flag);
                                if (Gamma_adjust_timeout_flag == true)
                                {
                                    flag1 = 0; flag3 = 0; flag2 = 0;
                                }
                                num_ILI8818_R17.Value = r;
                                num_ILI8818_G17.Value = g;
                                num_ILI8818_B17.Value = b;
                            }
                            break;
                        case 5:
                            {
                                Flexible_Gamma_auto_Adujst(flag1, flag3, flag2, lumg, lumr, lumb, D_lums[index, 1], D_lums[index, 0], D_lums[index, 2], num_ILI8818_R18.Value, num_ILI8818_G18.Value, num_ILI8818_B18.Value, Diven_Offset[index].NO, 0xfff, out r, out g, out b, out Gamma_adjust_timeout_flag);
                                if (Gamma_adjust_timeout_flag == true)
                                {
                                    flag1 = 0; flag3 = 0; flag2 = 0;
                                }
                                num_ILI8818_R18.Value = r;
                                num_ILI8818_G18.Value = g;
                                num_ILI8818_B18.Value = b;
                            }
                            break;
                        case 4:
                            {
                                Flexible_Gamma_auto_Adujst(flag1, flag3, flag2, lumg, lumr, lumb, D_lums[index, 1], D_lums[index, 0], D_lums[index, 2], num_ILI8818_R19.Value, num_ILI8818_G19.Value, num_ILI8818_B19.Value, Diven_Offset[index].NO, 0xfff, out r, out g, out b, out Gamma_adjust_timeout_flag);
                                if (Gamma_adjust_timeout_flag == true)
                                {
                                    flag1 = 0; flag3 = 0; flag2 = 0;
                                }
                                num_ILI8818_R19.Value = r;
                                num_ILI8818_G19.Value = g;
                                num_ILI8818_B19.Value = b;
                            }
                            break;
                        case 3:
                            {
                                Flexible_Gamma_auto_Adujst(flag1, flag3, flag2, lumg, lumr, lumb, D_lums[index, 1], D_lums[index, 0], D_lums[index, 2], num_ILI8818_R20.Value, num_ILI8818_G20.Value, num_ILI8818_B20.Value, Diven_Offset[index].NO, 0xfff, out r, out g, out b, out Gamma_adjust_timeout_flag);
                                if (Gamma_adjust_timeout_flag == true)
                                {
                                    flag1 = 0; flag3 = 0; flag2 = 0;
                                }
                                num_ILI8818_R20.Value = r;
                                num_ILI8818_G20.Value = g;
                                num_ILI8818_B20.Value = b;
                            }
                            break;
                        case 2:
                            {
                                //ILI8818_Gamma_auto_Adujst(flag1, flag3, flag2, 30, 3, 1, lumg, lumr, lumb, D_lums[2, 1], D_lums[2, 0], D_lums[2, 2], 120, num_ILI8818_R21.Value, num_ILI8818_G21.Value, num_ILI8818_B21.Value, Diven_Offset[index+2].NO, Diven_Offset[index+1].NO, Diven_Offset[index].NO, num_ILI8818_R23.Value, num_ILI8818_G23.Value, num_ILI8818_B23.Value, num_ILI8818_R22.Value, num_ILI8818_G22.Value, num_ILI8818_B22.Value, out r, out g, out b, out Gamma_adjust_timeout_flag);
                                Flexible_Gamma_auto_Adujst(flag1, flag3, flag2, lumg, lumr, lumb, D_lums[index, 1], D_lums[index, 0], D_lums[index, 2], num_ILI8818_R21.Value, num_ILI8818_G21.Value, num_ILI8818_B21.Value, Diven_Offset[index].NO, 0xfff, out r, out g, out b, out Gamma_adjust_timeout_flag);
                                if (Gamma_adjust_timeout_flag == true)
                                {
                                    flag1 = 0; flag3 = 0; flag2 = 0;
                                }
                                num_ILI8818_R21.Value = r;
                                num_ILI8818_G21.Value = g;
                                num_ILI8818_B21.Value = b;
                            }
                            break;
                        case 1:
                            {
                                //ILI8818_Gamma_auto_Adujst(flag1, flag3, flag2, 30, 3, 1, lumg, lumr, lumb, D_lums[index, 1], D_lums[index, 0], D_lums[index, 2], 120, num_ILI8818_R22.Value, num_ILI8818_G22.Value, num_ILI8818_B22.Value, Diven_Offset[index + 2].NO, Diven_Offset[index + 1].NO, Diven_Offset[index].NO, num_ILI8818_R23.Value, num_ILI8818_G23.Value, num_ILI8818_B23.Value, num_ILI8818_R23.Value, num_ILI8818_G23.Value, num_ILI8818_B23.Value, out r, out g, out b, out Gamma_adjust_timeout_flag);
                                Flexible_Gamma_auto_Adujst(flag1, flag3, flag2, lumg, lumr, lumb, D_lums[index, 1], D_lums[index, 0], D_lums[index, 2], num_ILI8818_R22.Value, num_ILI8818_G22.Value, num_ILI8818_B22.Value, Diven_Offset[index].NO, 0xfff, out r, out g, out b, out Gamma_adjust_timeout_flag);
                                if (Gamma_adjust_timeout_flag == true)
                                {
                                    flag1 = 0; flag3 = 0; flag2 = 0;
                                }
                                num_ILI8818_R22.Value = r;
                                num_ILI8818_G22.Value = g;
                                num_ILI8818_B22.Value = b;
                            }
                            break;
                        case 0:
                            {
                                //ILI8818_Gamma_auto_Adujst(flag1, flag3, flag2, 30, 3, 1, lumg, lumr, lumb, D_lums[index, 1], D_lums[index, 0], D_lums[index, 2], 120, num_ILI8818_R23.Value, num_ILI8818_G23.Value, num_ILI8818_B23.Value, Diven_Offset[index + 2].NO, Diven_Offset[index + 1].NO, Diven_Offset[index].NO, num_ILI8818_R23.Value, num_ILI8818_G23.Value, num_ILI8818_B23.Value, num_ILI8818_R23.Value, num_ILI8818_G23.Value, num_ILI8818_B23.Value, out r, out g, out b, out Gamma_adjust_timeout_flag);
                                Flexible_Gamma_auto_Adujst(flag1, flag3, flag2, lumg, lumr, lumb, D_lums[index, 1], D_lums[index, 0], D_lums[index, 2], num_ILI8818_R23.Value, num_ILI8818_G23.Value, num_ILI8818_B23.Value, Diven_Offset[index].NO, 0xfff, out r, out g, out b, out Gamma_adjust_timeout_flag);
                                if (Gamma_adjust_timeout_flag == true)
                                {
                                    flag1 = 0; flag3 = 0; flag2 = 0;
                                }
                                num_ILI8818_R23.Value = r;
                                num_ILI8818_G23.Value = g;
                                num_ILI8818_B23.Value = b;
                            }
                            break;
                        default:
                            break;

                            #endregion
                            #region
                            //    case 0:
                            //    case 1:
                            //    case 2:
                            //    case 3:
                            //    case 4:
                            //    case 5:
                            //    case 6:
                            //    case 7:
                            //    case 8:
                            //    case 9:
                            //    case 10:
                            //    case 11:
                            //    case 12:
                            //    case 13:
                            //    case 14:
                            //    case 15:
                            //    case 16:
                            //    case 17:
                            //    case 18:
                            //    case 19:
                            //    case 20:
                            //    case 21:
                            //    case 22:
                            //    case 23:
                            //        {
                            //            if (flag3 == 1)
                            //            {   //GammaUpSpeed(int frgb, double targetlum, double nowlum, int nowpoint, int nowRegValue, int lastpoint, int lastRegValue, out int nowRegValueAdj)
                            //                frgb = 1;
                            //                GammaUpSpeed(frgb, D_lums[index, 0], lumr, Point_ILI8818[index], RGBValue[index, 0], Point_ILI8818[index], RGBValue[index, 0], out int nowRegValueAdj);

                            //                if (nowRegValueAdj > 0)
                            //                {
                            //                    RGBValue[index, 1] = nowRegValueAdj;    //数据更新至数组
                            //                    RGBValueSet(array2value, index, 0, 0);

                            //                }
                            //                else
                            //                {
                            //                    T20.Enabled = false;
                            //                    //MessageBoxTimeoutA((IntPtr)0, "R自动调节失败，请手动调试", "ERROR", 16, 0, 100);
                            //                    //MessageBox.Show("R 自动调节失败，请手动重试");
                            //                }
                            //            }
                            //            if (flag2 == 1)
                            //            {
                            //                //private void GammaUpSpeed(double targetlum, double nowlum, int nowpoint, int nowRegValue,  int lastpoint,int lastRegValue, out int nowRegValueAdj);
                            //                frgb = 2;
                            //                GammaUpSpeed(frgb, D_lums[index, 1], lumg, Point_ILI8818[index], RGBValue[index, 1], Point_ILI8818[index - 0], RGBValue[index - 0, 1], out int nowRegValueAdj);

                            //                if ((nowRegValueAdj > 0))//&& (nowRegValueAdj <= RGBValue[index - 1, 1] + 10))
                            //                {
                            //                    RGBValue[index, 1] = nowRegValueAdj;    //数据更新至数组
                            //                    RGBValueSet(array2value, index, 1, 0);
                            //                }
                            //                else
                            //                {
                            //                    T20.Enabled = false;
                            //                    //MessageBoxTimeoutA((IntPtr)0, "G自动调节失败，请手动调试", "ERROR", 16, 0, 100);
                            //                    //MessageBox.Show("G 自动调节失败，请手动重试");
                            //                }

                            //            }
                            //            if (flag1 == 1)
                            //            {
                            //                frgb = 3;
                            //                GammaUpSpeed(frgb, D_lums[index, 2], lumb, Point_ILI8818[index], RGBValue[index, 2], Point_ILI8818[index - 0], RGBValue[index - 0, 2], out int nowRegValueAdj);

                            //                if ((nowRegValueAdj > 0))// && (nowRegValueAdj <= RGBValue[index - 1, 2] + 10))
                            //                {
                            //                    RGBValue[index, 2] = nowRegValueAdj;    //数据更新至数组
                            //                    RGBValueSet(array2value, index, 2, 0);
                            //                }
                            //                else
                            //                {
                            //                    T20.Enabled = false;
                            //                    //MessageBoxTimeoutA((IntPtr)0, "B自动调节失败，请手动调试", "ERROR", 16, 0, 100);
                            //                    //MessageBox.Show("B 自动调节失败，请手动重试");
                            //                }

                            //            }
                            //               frmHelp.auto_gamma_write(gamma_r[total_points - 1 - index], Convert.ToUInt16(RGBValue[index, 0]), gamma_g[total_points - 1 - index], Convert.ToUInt16(RGBValue[index, 1]), gamma_b[total_points - 1 - index], Convert.ToUInt16(RGBValue[index, 2]));
                            //                Thread.Sleep(20);
                            //            //auto_gamma_write(gamma_r[23 - index], (UInt16)RGBValue[index, 0], gamma_g[23 - index], (UInt16)RGBValue[index, 1], gamma_b[23 - index], (UInt16)RGBValue[index, 2]);
                            //            GammaAdjustTimes++;

                            //        //else { index++; }
                            //        break;
                            //}
                            #endregion

                    }
                    #region//---风神算法
                    if (index != 23)
                    {
                        Reg_E3_locked(1, e);//解锁
                        frmHelp.auto_gamma_write((UInt16)(total_points - 1 - index), Convert.ToUInt16(r), (UInt16)(total_points - 1 - index), Convert.ToUInt16(g), (UInt16)(total_points - 1 - index), Convert.ToUInt16(b));
                        Reg_E3_locked(0, e);//上锁
                        //Thread.Sleep(20);
                    }
                    else
                    {
                        Reg_E3_locked(1, e);//解锁
                        frmHelp.auto_gamma_write((UInt16)(total_points - 1 - index), 0, (UInt16)(total_points - 1 - index), 0, (UInt16)(total_points - 1 - index), 0);
                        Reg_E3_locked(0, e);//上锁
                        T20.Enabled = false;
                    }
                    #endregion
                }
                catch
                {
                    T20.Enabled = false;
                    MessageBox.Show("调整数值超限");
                }
            }
        }

        #region  //--------------------风神算法------------------
        /*
        输出：15，16，17、目标绑点R/G/B寄存器输出值；
              18、超时提醒
        */
        //public decimal Red_Ratio = 0xf;
        //public decimal Green_Ratio = Convert.ToDecimal();
        //public decimal Blue_Ratio = Convert.ToDecimal();
        //--------------系数----------------------------------------------------
        public decimal Last_reg_red = 0;
        public decimal Last_reg_green = 0;
        public decimal Last_reg_blue = 0;
        //--------------多组计算------------------------------------------------
        private ArrayList flexible_gamma_point_list = new ArrayList(); //存储灰阶
        private ArrayList flexible_gamma_reg_red = new ArrayList();    //存储每阶R寄存器
        private ArrayList flexible_gamma_reg_green = new ArrayList();  //存储每阶G寄存器
        private ArrayList flexible_gamma_reg_blue = new ArrayList();   //存储每阶B寄存器
        //--------------单段计算------------------------------------------------
        private static decimal[,] Past_Reg_stack = new decimal[3, 250];  //存储每跳步R/G/B寄存器值
        private static double[,] Past_lum_stack = new double[3, 250];    //存储每跳步R/G/B分亮度值   
        private static double[] BCompare0 = new double[250];
        //--------------单点加速------------------------------------------------
        private static bool Register_jump_flag = false;
        private static bool Register_lum_jump_flag = false;
        //public bool Gamma_adjust_timeout_flag = false;
        public int Gamma_auto_adjust_count = 0;
        public int Gamma_auto_adjust_count_temp = 0;
        //--------------单色加速-------------------------------------------------
        private static int Y_adjust_count = 0;
        private static int X_adjust_count = 0;
        //-----------------------------------------------------------------------
        private static int Steph = 0, Stepm = 0, Stepl = 0;
        //-----------------------------------------------------------------------
        /// <summary>
        /// Gamma绑点寄存器调整
        /// </summary>
        /// <param name="lum_adjust_enable">亮度分量调整使能</param>
        /// <param name="x_adjust_enable">X色坐标分量调整使能</param>
        /// <param name="y_adjust_enable">Y色坐标分量调整使能</param>
        /// <param name="measure_lum">计算实际测量亮度分量</param>
        /// <param name="measure_x">计算实际测量X色坐标分量</param>
        /// <param name="measure_y">计算实际测量Y色坐标分量</param>
        /// <param name="target_lum">目标亮度分量</param>
        /// <param name="target_x">目标X色坐标分量</param>
        /// <param name="target_y">目标Y色坐标分量</param>
        /// <param name="input_reg_red">输入_R_寄存器值</param>
        /// <param name="input_reg_green">输入_G_寄存器值</param>
        /// <param name="input_reg_blue">输入_B_寄存器值</param>
        /// <param name="gary_target">目标灰阶值</param>
        /// <param name="reg_range">寄存器调整范围</param>
        /// <param name="output_reg_red">输出_R_寄存器值</param>
        /// <param name="output_reg_green">输出_G_寄存器值</param>
        /// <param name="output_reg_blue">输出_B_寄存器值</param>
        /// <param name="timeout_flag">调节超时标志位</param>
        public void Flexible_Gamma_auto_Adujst(
        int lum_adjust_enable, int x_adjust_enable, int y_adjust_enable,
        double measure_lum, double measure_x, double measure_y,
        double target_lum, double target_x, double target_y,
        decimal input_reg_red, decimal input_reg_green, decimal input_reg_blue,
        int gary_target, int reg_range,
        //output
        out decimal output_reg_red, out decimal output_reg_green, out decimal output_reg_blue, out bool timeout_flag)
        {
            int step_tmp = 0;
            double max_h, min_h, max_m, min_m;
            int adjust_times, shake_times;
            double target_reference;
            decimal reg_reference;
            int reg_approach = 0;
            timeout_flag = false;
            output_reg_red = input_reg_red;
            output_reg_green = input_reg_green;
            output_reg_blue = input_reg_blue;
            target_reference = target_lum + target_x + target_y;
            //自动单绑点调节次数
            if (reg_range > 0x7ff) //FFF~800
            {
                adjust_times = 120;
            }
            else if (reg_range > 0x3ff) //7ff~400
            {
                adjust_times = 90;
            }
            else
            {
                adjust_times = 70;
            }
            try
            {
                if (Gamma_auto_adjust_count <= adjust_times)
                {
                    if (Gamma_auto_adjust_count == 0)//firstly!clear buffer 
                    {
                        //根据可调range，自动定义步长，随灰阶绑点逐渐从Max减小至Min
                        max_h = 50.13 * Math.Sin(0.0003539 * reg_range + 0.04827);
                        min_h = 30.06 * Math.Sin(0.0003796 * reg_range - 0.04927);
                        max_m = 25.03 * Math.Sin(0.0004312 * reg_range - 0.24);
                        min_m = 13.11 * Math.Sin(0.0002326 * reg_range - 0.08475);
                        Steph = (int)(gary_target / 255 * max_h + min_h);
                        Stepm = (int)(gary_target / 255 * max_m + min_m);
                        Stepl = 1;

                        if (gary_target == 255)//如果是每组的第一个绑点，清空List
                        {
                            flexible_gamma_point_list.Clear();
                            flexible_gamma_reg_red.Clear();
                            flexible_gamma_reg_green.Clear();
                            flexible_gamma_reg_blue.Clear();
                        }

                        Register_jump_flag = false;
                        Register_lum_jump_flag = false;
                        //记录上个绑点调节最佳值
                        Last_reg_red = Past_Reg_stack[0, Gamma_auto_adjust_count_temp];
                        Last_reg_green = Past_Reg_stack[1, Gamma_auto_adjust_count_temp];
                        Last_reg_blue = Past_Reg_stack[2, Gamma_auto_adjust_count_temp];

                        //灰阶 list 有效数据从buffer[0]开始记录
                        //    flexible_gamma_point_list.Add(target_gray);
                        //RGB寄存器 list 在数据清空前记录每阶绑点最佳值,有效数据从buffer[1]开始记录
                        flexible_gamma_reg_red.Add(Last_reg_red);
                        flexible_gamma_reg_green.Add(Last_reg_green);
                        flexible_gamma_reg_blue.Add(Last_reg_blue);

                        Past_Reg_stack = new decimal[3, 250];
                        Past_lum_stack = new double[3, 250];
                        BCompare0 = new double[250];
                        Gamma_auto_adjust_count_temp = 0;//清“0”重新开始统计

                        //加速跳转
                        if ((gary_target != 255) && (Math.Abs(measure_lum - target_lum) > target_lum * 10 / 100) && (((input_reg_red > Last_reg_red) || (input_reg_red < Last_reg_red - 0x70)) || ((input_reg_green > Last_reg_green) || (input_reg_green < Last_reg_green - 0x70)) || ((input_reg_blue > Last_reg_blue) || (input_reg_blue < Last_reg_blue - 0x70)))) //R/G/B启动初始值干预   ,此处判断条件后面改掉!!
                        {
                            output_reg_red = Last_reg_red - Convert.ToDecimal(txt_gamma_adj_step.Text); //减去多少值后续由计算得出，此处暂定减去0xf
                            output_reg_green = Last_reg_green - Convert.ToDecimal(txt_gamma_adj_step.Text);
                            output_reg_blue = Last_reg_blue - Convert.ToDecimal(txt_gamma_adj_step.Text);
                            //output_reg_red = (decimal)(Math.Pow((double)(gary_target) * 190.5 , 0.3498));
                            //output_reg_green = (decimal)(Math.Pow((double)(gary_target) * 173.3, 0.3609));
                            //output_reg_blue = (decimal)(Math.Pow((double)(gary_target) * 207.3, 0.3514));

                            Gamma_auto_adjust_count = Gamma_auto_adjust_count + 1;
                            Gamma_auto_adjust_count_temp = Gamma_auto_adjust_count;//记录最佳值地址指针
                            goto Jump_to_end;
                        }
                        else//debug
                        {
                            frmHelp.textBox1.Text = frmHelp.textBox1.Text + "gary_target" + gary_target.ToString() + "\r\n";
                            frmHelp.textBox1.Text = frmHelp.textBox1.Text + "input_reg_red" + input_reg_red.ToString() + "\r\n";
                            frmHelp.textBox1.Text = frmHelp.textBox1.Text + "input_reg_green" + input_reg_green.ToString() + "\r\n";
                            frmHelp.textBox1.Text = frmHelp.textBox1.Text + "input_reg_blue" + input_reg_blue.ToString() + "\r\n";
                        }
                    }
                    Gamma_auto_adjust_count = Gamma_auto_adjust_count + 1;
                    Gamma_auto_adjust_count_temp = Gamma_auto_adjust_count;//记录最佳值地址指针

                    Past_Reg_stack[0, Gamma_auto_adjust_count] = input_reg_red;
                    Past_Reg_stack[1, Gamma_auto_adjust_count] = input_reg_green;
                    Past_Reg_stack[2, Gamma_auto_adjust_count] = input_reg_blue;
                    Past_lum_stack[0, Gamma_auto_adjust_count] = measure_x;
                    Past_lum_stack[1, Gamma_auto_adjust_count] = measure_lum;
                    Past_lum_stack[2, Gamma_auto_adjust_count] = measure_y;
                    BCompare0[Gamma_auto_adjust_count] = measure_x + measure_y + measure_lum;

                    if (x_adjust_enable == 1)
                    {
                        if (Math.Abs(measure_x - target_x) > target_x * 20 / 100)
                        {
                            if (target_lum < 1)
                            { step_tmp = Stepm; }
                            else
                            { step_tmp = Steph; }
                        }
                        else if (Math.Abs(measure_x - target_x) > target_x * 2 / 100)
                        {
                            if (target_lum < 1) //if lower target lum
                            { step_tmp = Stepl; }
                            else
                            { step_tmp = Stepm; }
                        }
                        else
                        {
                            step_tmp = Stepl;
                            X_adjust_count++;
                        }
                        if ((Gamma_auto_adjust_count > 5) && (Past_Reg_stack[0, Gamma_auto_adjust_count] == Past_Reg_stack[0, Gamma_auto_adjust_count - 2])) //滤掉第一次采样波动值
                        {
                            step_tmp = step_tmp / 2;
                            if (step_tmp < 1)
                            {
                                step_tmp = Stepl;
                            }
                        }
                        if (measure_x > target_x)
                            output_reg_red = input_reg_red - step_tmp;
                        else output_reg_red = input_reg_red + step_tmp;
                    }
                    //-----------------------------------------------
                    if (lum_adjust_enable == 1)
                    {
                        Y_adjust_count = 0;
                        X_adjust_count = 0;
                        if (Math.Abs(measure_lum - target_lum) > target_lum * 20 / 100)
                        {
                            if (target_lum < 1)
                            { step_tmp = Stepm; }
                            else
                            { step_tmp = Steph; }
                        }
                        else if (Math.Abs(measure_lum - target_lum) > target_lum * 2 / 100)
                        {
                            if (target_lum < 1)
                            { step_tmp = Stepl; }
                            else
                            { step_tmp = Stepm; }
                        }
                        else
                        {
                            step_tmp = Stepl;
                        }
                        //-------------------------step幅值干预---------------------------------
                        if ((gary_target == 255) && (Gamma_auto_adjust_count >= 3) && (Register_lum_jump_flag == false) && (measure_lum > 0)) //滤掉第一次采样波动值
                        {
                            if ((Math.Abs(measure_lum - target_lum) > target_lum * 30 / 100))//无需亮度过调
                            {
                                reg_approach = (int)(Math.Abs((int)(Past_Reg_stack[1, Gamma_auto_adjust_count] - Past_Reg_stack[1, Gamma_auto_adjust_count - 2])) * ((double)(target_lum / Math.Abs((Past_lum_stack[1, Gamma_auto_adjust_count] - Past_lum_stack[1, Gamma_auto_adjust_count - 2])))));
                                if (reg_approach > 0 && reg_approach < 0x3ff)
                                {
                                    step_tmp = reg_approach; //加速亮度逼近目标值
                                }
                            }
                            else
                            {
                                Register_lum_jump_flag = true;//停止加速
                            }
                        }
                        if ((Gamma_auto_adjust_count > 5) && (Past_Reg_stack[1, Gamma_auto_adjust_count] == Past_Reg_stack[1, Gamma_auto_adjust_count - 2]))
                        {
                            step_tmp = step_tmp / 2;
                            if (step_tmp < Stepl)
                            {
                                step_tmp = Stepl;
                            }
                        }
                        if (measure_lum > target_lum)
                            output_reg_green = input_reg_green - step_tmp;
                        else output_reg_green = input_reg_green + step_tmp;
                    }
                    //-----------------------------------------
                    if (y_adjust_enable == 1)
                    {
                        X_adjust_count = 0;
                        {
                            if (Math.Abs(measure_y - target_y) > target_y * 20 / 100)
                            {
                                if (target_lum < 1)
                                { step_tmp = Stepm; }
                                else
                                { step_tmp = Steph; }
                            }
                            else if (Math.Abs(measure_y - target_y) > target_y * 2 / 100)
                            {
                                if (target_lum < 1)
                                { step_tmp = Stepl; }
                                else
                                { step_tmp = Stepm; }
                            }
                            else
                            {
                                step_tmp = Stepl;
                                Y_adjust_count++;
                            }
                            if ((Gamma_auto_adjust_count > 5) && (Past_Reg_stack[2, Gamma_auto_adjust_count] == Past_Reg_stack[2, Gamma_auto_adjust_count - 2])) //滤掉第一次采样波动值
                            {
                                step_tmp = step_tmp / 2;
                                if (step_tmp < 1)
                                {
                                    step_tmp = Stepl;
                                }
                            }
                            if (measure_y > target_y)
                                output_reg_blue = input_reg_blue - step_tmp;
                            else output_reg_blue = input_reg_blue + step_tmp;
                        }
                    }

                    //----------------------------------------------------------------------------
                    if ((Math.Abs(BCompare0[Gamma_auto_adjust_count] - target_reference) < target_reference * (int)(1 - (double)((double)(gary_target / 255) * 0)) / 100))//进入防抖范围
                    {
                        if ((step_tmp == Stepl) || (Stepl == Stepm))
                        {
                            if ((BCompare0[Gamma_auto_adjust_count - 2] > BCompare0[Gamma_auto_adjust_count - 1]) && (Math.Abs(BCompare0[Gamma_auto_adjust_count - 2] - target_reference) < target_reference * (int)(1 - (double)((double)(gary_target / 255) * 0)) / 100) && (Math.Abs(BCompare0[Gamma_auto_adjust_count - 1] - target_reference) < target_reference * (int)(1 - (double)((double)(gary_target / 255) * 0)) / 100))
                            {
                                if (BCompare0[Gamma_auto_adjust_count - 1] > BCompare0[Gamma_auto_adjust_count])
                                {
                                    if ((Y_adjust_count > 3) && (lum_adjust_enable != 1))
                                    // if (((Y_adjust_count > 3)&& (lum_adjust_enable != 1))||((x_adjust_enable!=1)&&((Math.Abs(measure_lum - target_lum) < target_lum * 2 / 100))))
                                    {
                                        if ((Math.Abs(measure_y - target_y) < target_y * 1 / 100) && (Math.Abs(measure_lum - target_lum) < target_lum * 1 / 100))
                                        {
                                            if (measure_y > target_y)
                                            {
                                                output_reg_green = input_reg_green - Stepl;
                                            }
                                            else if (measure_y < target_y)
                                            {
                                                output_reg_green = input_reg_green + Stepl;
                                            }
                                        }
                                        Y_adjust_count = 0;
                                    }
                                    /*
                                    if ((Math.Abs(measure_y - target_y) < target_y * 5 / 1000) && (Math.Abs(measure_x - target_x) < target_x * 5 / 1000) && (Math.Abs(measure_lum - target_lum) < target_lum * 1.5 / 100))
                                    {
                                        Gamma_auto_adjust_count = adjust_times;
                                    }
                                    if ((X_adjust_count > 3) && (y_adjust_enable != 1) && (lum_adjust_enable != 1))
                                    {
                                        if (Math.Abs(measure_x - target_x) < target_x * 7 / 100)
                                        {
                                            X_adjust_count = 0;
                                            Gamma_auto_adjust_count = adjust_times;
                                        }
                                    }
                                    */
                                }
                                else
                                {
                                    output_reg_red = Past_Reg_stack[0, Gamma_auto_adjust_count];
                                    output_reg_green = Past_Reg_stack[1, Gamma_auto_adjust_count];
                                    output_reg_blue = Past_Reg_stack[2, Gamma_auto_adjust_count];
                                    timeout_flag = true;
                                    frmHelp.textBox1.Text = frmHelp.Text + "pass directly!!\r\n";
                                }
                            }
                            else
                            {
                                ;
                            }
                        }
                        else if (step_tmp == Stepm)
                        {
                            Stepm = Stepm / 2;
                            if (Stepm < Stepl)
                            {
                                Stepm = Stepl;
                            }
                            /*
                                                        if ((Y_adjust_count > 3) && (lum_adjust_enable != 1))
                                                        {
                                                            if ((Math.Abs(measure_y - target_y) < target_y * 5 / 100) && (Math.Abs(measure_lum - target_lum) < target_lum * 2 / 100))
                                                            {
                                                                if (measure_y > target_y)
                                                                {
                                                                    output_reg_green = input_reg_green - Stepl;
                                                                }
                                                                else if (measure_y < target_y)
                                                                {
                                                                    output_reg_green = input_reg_green + Stepl;
                                                                }
                                                            }
                                                            Y_adjust_count = 0;
                                                        }
                                                        */
                        }
                        else if (step_tmp == Steph)
                        {
                            Steph = Steph / 2;
                            if (Steph < Stepm)
                            {
                                Steph = Stepm;
                            }
                        }
                    }

                    //----------------------------------若数值超限--------------------------------------                 
                    /*if (((output_reg_red < 30) || (output_reg_red > index2_reg_red) || (output_reg_green < 30) || (output_reg_green > index2_reg_green) || (output_reg_blue < 30) || (output_reg_blue > index2_reg_blue)) && ((target_lum * 95 / 100 < measure_lum) && (target_lum * 105 / 100 > measure_lum)))
                    {
                        output_reg_red = Convert.ToInt16(index1_reg_red - Math.Abs(index2_reg_red - index1_reg_red) / (gary_last_index2 - gary_last_index1) * (gary_last_index1 - gary_target));
                        output_reg_green = Convert.ToInt16(index1_reg_green - Math.Abs(index2_reg_green - index1_reg_green) / (gary_last_index2 - gary_last_index1) * (gary_last_index1 - gary_target));
                        output_reg_blue = Convert.ToInt16(index1_reg_blue - Math.Abs(index2_reg_blue - index1_reg_blue) / (gary_last_index2 - gary_last_index1) * (gary_last_index1 - gary_target));
                    //  textBox1.Text = "该绑点R/G/B插值迭代/r/n";
                        Gamma_auto_adjust_count = 0;
                        timeout_flag = true;
                    }*/
                }
                else
                {
                    Y_adjust_count = 0;
                    // textBox1.Text += "Timeout!\r\n";
                    Gamma_auto_adjust_count = 0;
                    timeout_flag = true;
                    /*
                    if (output_reg_red > index1_reg_red)
                    {
                        output_reg_red = index1_reg_red - Math.Abs(index2_reg_red - index1_reg_red) / (gary_last_index2 - gary_last_index1) * (gary_last_index1 - gary_target);
                        // textBox1.Text += "该绑点R差值迭代/r/n";
                    }
                    if (output_reg_green > index1_reg_green)
                    {
                        output_reg_green = index1_reg_green - Math.Abs(index2_reg_green - index1_reg_green) / (gary_last_index2 - gary_last_index1) * (gary_last_index1 - gary_target);
                        //  textBox1.Text += "该绑点G差值迭代/r/n";
                    }
                    if (output_reg_blue > index1_reg_blue)
                    {
                        output_reg_blue = index1_reg_blue - Math.Abs(index2_reg_blue - index1_reg_blue) / (gary_last_index2 - gary_last_index1) * (gary_last_index1 - gary_target);
                        //  textBox1.Text += "该绑点B差值迭代/r/n";
                    }
                    */
                }
                output_reg_red = Convert.ToInt32(output_reg_red);
                output_reg_green = Convert.ToInt32(output_reg_green);
                output_reg_blue = Convert.ToInt32(output_reg_blue);

                if ((Gamma_auto_adjust_count > 2) && (lum_adjust_enable == 0) && (Register_jump_flag == false)) // only inter once time
                {
                    Register_jump_flag = true; // 只跳转一次
                    reg_reference = Math.Abs(Last_reg_green - Past_Reg_stack[1, Gamma_auto_adjust_count]); //得出差值

                    if (Math.Abs(measure_y - target_y) > target_y * 10 / 100)
                    {
                        if (Last_reg_green > Past_Reg_stack[1, Gamma_auto_adjust_count])
                        {
                            output_reg_blue = Last_reg_blue - reg_reference;
                        }
                        else
                        {
                            output_reg_blue = Last_reg_blue + reg_reference;
                        }
                    }
                    if (Math.Abs(measure_x - target_x) > target_x * 10 / 100)
                    {
                        if (Last_reg_green > Past_Reg_stack[1, Gamma_auto_adjust_count])
                        {
                            output_reg_red = Last_reg_red - reg_reference;
                        }
                        else
                        {
                            output_reg_red = Last_reg_red + reg_reference;
                        }
                    }
                }
            Jump_to_end:;
            }
            catch
            {
                ;
            }
        }
        #endregion
        #region//——————————胡哥算法—————————
        private static bool GammaAdjustTimeoutFlag = false;
        private static int GammaAdjustTimes = 0;
        //--------------------------------------------------------
        private int teppoint = 1; //记录绑点是否变更        
        private int frgb = 1;     //当前调节RGB标志， 1:r;2:G;3:B;

        int step_tmpr = 64, step_tmpg = 64, step_tmpb = 64;//调节初始步长
        bool fdirr = true;
        bool fdirg = true;
        bool fdirb = true;
        private void GammaUpSpeed(int frgb, double targetlum, double nowlum, int nowpoint, int nowRegValue, int lastpoint, int lastRegValue, out int nowRegValueAdj)
        {

            if ((nowRegValue > lastRegValue) && (index > 3))
            {
                nowRegValue = lastRegValue - 1;
            }
            if ((teppoint != nowpoint))
            {
                teppoint = nowpoint;
                step_tmpr = 64;
                step_tmpg = 64;
                step_tmpb = 64;
                if (nowlum > targetlum) //初始化调节方向
                {
                    if (frgb == 1) fdirr = true; //向前瞄准目标数据
                    else if (frgb == 2) fdirg = true;
                    else if (frgb == 3) fdirb = true;
                }
                else
                {
                    if (frgb == 1) fdirr = false;
                    else if (frgb == 2) fdirg = false;
                    else if (frgb == 3) fdirb = false;
                }
            }
            nowRegValueAdj = nowRegValue - 0;

            if (nowlum > targetlum)
            {
                if (frgb == 1)
                {
                    if (!fdirr)//判断前进方向是否瞄准目标点
                    {
                        if (step_tmpr > 1) step_tmpr >>= 1;
                    }
                    nowRegValueAdj = nowRegValue - step_tmpr;
                    fdirr = true;
                }
                else if (frgb == 2)
                {
                    if (!fdirg)
                    {
                        if (step_tmpg > 1) step_tmpg >>= 1;

                    }
                    nowRegValueAdj = nowRegValue - step_tmpg;
                    fdirg = true;
                }
                else if (frgb == 3)
                {
                    if (!fdirr)
                    {
                        if (step_tmpb > 1) step_tmpb >>= 1;
                    }

                    nowRegValueAdj = nowRegValue - step_tmpb;
                    fdirb = true;
                }

            }
            else if (nowlum < targetlum)
            {
                if (frgb == 1)
                {
                    if (fdirr)
                    {
                        if ((step_tmpr > 1)) step_tmpr >>= 1;
                    }
                    nowRegValueAdj = nowRegValue + step_tmpr;
                    fdirr = false;
                }
                else if (frgb == 2)
                {
                    if (fdirg)
                    {
                        if ((step_tmpg > 1)) step_tmpg >>= 1;
                    }
                    nowRegValueAdj = nowRegValue + step_tmpg;
                    fdirg = false;
                }
                else if (frgb == 3)
                {
                    if (fdirb)
                    {
                        if ((step_tmpb > 1)) step_tmpb >>= 1;
                    }
                    nowRegValueAdj = nowRegValue + step_tmpb;
                    fdirb = false;
                }
            }
            frgb = 0;
            if (nowRegValueAdj > 0xffe)
            {
                nowRegValueAdj = 0x7f0;
                frmHelp.textBox1.Text += "Over 0x7FF \r\n";
                frmHelp.textBox1.Select(frmHelp.textBox1.Text.Length, 0);
                frmHelp.textBox1.ScrollToCaret();
            }
            else if (nowRegValueAdj < 1)
            {
                nowRegValueAdj = 10;
                frmHelp.textBox1.Text += "GammaValue <1，检查显示 \r\n";
                frmHelp.textBox1.Select(frmHelp.textBox1.Text.Length, 0);
                frmHelp.textBox1.ScrollToCaret();
            }

        }
        #endregion
        private void ILI8818_Others_Click(object sender, EventArgs e)
        {
            Send_buf = new byte[50];
            Button btnTmp = (Button)sender;
            Setting.TempRecord.cmdLen = 50;

            Send_buf[0] = 0x6F;        //ILI8818
            Send_buf[2] = 0x02;
            switch (btnTmp.Name)
            {
                case "btn_Reg_W":         //W写寄存器   1
                    {
                        string strLine = Convert.ToString(txt_Reg_Data_WR.Text);
                        string[] arr = strLine.Split(','); //以逗号分割，添加到数组

                        Setting.TempRecord.cmdLen = arr.Length + 5;
                        Send_buf = new byte[arr.Length + 5];
                        Send_buf[0] = 0x6F; //
                        Send_buf[1] = 0x01; //寄存器写
                        Send_buf[2] = byte.Parse(arr.Length.ToString());
                        for (int i = 0; i < arr.Length; i++)
                        {
                            Send_buf[3 + i] = byte.Parse((Convert.ToInt32(arr[i], 16)).ToString());
                        }
                    }
                    break;
                case "btn_Reg_R":         //R读寄存器    2
                    {
                        string strLine = Convert.ToString(txt_Reg_Data_WR.Text);
                        string[] arr = strLine.Split(','); //以逗号分割，添加到数组
                        int DataNum = Convert.ToByte(txt_return_num_RW.Text);
                        Setting.TempRecord.cmdLen = DataNum + 1 + 5;
                        Send_buf = new byte[DataNum + 1 + 5];

                        Send_buf[0] = 0x6F;
                        Send_buf[1] = 0x02; //寄存器读
                        Send_buf[2] = Convert.ToByte(DataNum + 1);//length
                        Send_buf[3] = byte.Parse((Convert.ToInt32(arr[0], 16)).ToString());//register
                    }
                    break;
                default:
                    break;
            }
            CRCData.CalculateCrc16(Send_buf, out Send_buf[Send_buf[2] + 3], out Send_buf[Send_buf[2] + 4]);
            try
            {
                frmHelp.comPort.Write(Send_buf, 0, Send_buf[2] + 5);
            }
            catch
            {
                MessageBox.Show("串口有误，请检查", "错误");
                return;
            }
            frmHelp.T1.Enabled = false;
            frmHelp.T1.Interval = 2000;
            frmHelp.T1.Enabled = true;
        }

        private void trb_DBV_TrackBar_Scroll(object sender, EventArgs e)
        {
            int bits_51h = Convert.ToInt16(Math.Pow(2, Convert.ToByte(txt_51h_Bits.Text))) - 1;
            lab_trackBar_Display.Text = bits_51h + "阶";
            trb_DBV_TrackBar.Maximum = bits_51h;
            txt_Reg_Data_WR.Text = "ff,78,38,00";
            ILI8818_Others_Click(btn_Reg_W, e);
            //txt_Reg_Data_WR.Text = "51,03";//需要重新写入命令
            //ILI8818_Others_Click(btn_Reg_W, e);

            if (bits_51h < 0x100)
            {
                txt_Reg_Data_WR.Text = "51," + trb_DBV_TrackBar.Value.ToString("x2");
            }
            else
            {
                txt_Reg_Data_WR.Text = "51" + "," + trb_DBV_TrackBar.Value.ToString("x4").Substring(0, 2) + "," + trb_DBV_TrackBar.Value.ToString("x4").Substring(2, 2);
            }
            ILI8818_Others_Click(btn_Reg_W, e);
        }

        #region//-------------------------De-Mura Function--------------------
        private void Demura_Click(object sender, EventArgs e)
        {
            Button btnTmp = (Button)sender;
            Send_buf = new byte[10];
            Setting.TempRecord.cmdLen = 10;
            Send_buf[0] = 0x2F;
            Send_buf[2] = 0x05;
            Send_buf[3] = 0x29;
            switch (btnTmp.Name)
            {
                case "btn_DeMura_Flash_IDRead":
                    {
                        Send_buf[1] = 0x01;
                        if (ILI_518.Checked == true) Send_buf[1] = (byte)(Send_buf[1] + 0XE0);
                    }
                    break;

                case "btn_DeMura_Flash_Setting":
                    {
                        Send_buf[1] = 0x02;
                        if (ILI_518.Checked == true) Send_buf[1] = (byte)(Send_buf[1] + 0XE0);
                    }
                    break;

                case "btn_DeMura_Load_Data":
                    {
                        Send_buf[1] = 0x03;
                        PreLoad_Demura_data_Click();
                    }
                    break;

                case "btn_DeMura_RAM_Disable":
                    {
                        Send_buf[1] = 0x04;
                    }
                    break;

                case "btn_DeMura_Flash_Erase":
                    {
                        Send_buf[1] = 0x05;
                        MessageBox.Show("擦除时间大约持续10s，请耐心等待擦除完成弹窗。");
                    }
                    break;

                case "btn_DeMura_Flash_Wrting":
                    {
                        Send_buf[1] = 0x06;
                        MessageBox.Show("烧录数据大约需要5s，等待返回De-Mura Data Writing Successful.信息");
                    }
                    break;

                case "btn_DeMura_Reload_Data":
                    {

                        Send_buf[1] = 0x07;
                    }
                    break;

                case "btn_DeMura_Check_CRC":
                    {
                        Send_buf[1] = 0x08;
                    }
                    break;

                case "btn_DeMura_Function_On":
                    {
                        Send_buf[1] = 0x09;
                        if (ILI_518.Checked == true) Send_buf[1] = (byte)(Send_buf[1] + 0XE0);
                    }
                    break;

                case "btn_DeMura_Function_Off":
                    {
                        Send_buf[1] = 0x0A;
                        if (ILI_518.Checked == true) Send_buf[1] = (byte)(Send_buf[1] + 0XE0);
                    }
                    break;
                default:
                    frmHelp.textBox1.Text = "DeMura 按键异常！！";
                    break;
            }
            CRCData.CalculateCrc16(Send_buf, out Send_buf[8], out Send_buf[9]);
            try
            {
                frmHelp.comPort.Write(Send_buf, 0, 10);
            }
            catch
            {
                MessageBox.Show("串口有误，请检查", "错误");
                return;
            }
        }

        //测试计算功能
        private void btn_calc_Click(object sender, EventArgs e)
        {
            //===========From initial code===================//
            int Gamma_Point_Num = 24;  //GAMMA 綁點個數
            int[] N1_GammaPoint = new int[24] { 0, 1, 3, 5, 9, 13, 17, 22, 29, 35, 41, 51, 65, 81, 93, 104, 114, 134, 159, 177, 198, 225, 247, 255 }; // GAMMA 綁點位置 0~255, 
            int[][] N1_Gamma_Index = new int[3][];
            //N1_Gamma_Index[0] = new int[24] { 0, 521, 626, 748, 937, 1086, 1213, 1348, 1504, 1620, 1725, 1881, 2072, 2263, 2391, 2501, 2595, 2780, 2997, 3149, 3320, 3536, 3714, 3778 };        //R
            //N1_Gamma_Index[1] = new int[24] { 0, 517, 587, 668, 840, 990, 1118, 1256, 1413, 1528, 1633, 1784, 1973, 2159, 2287, 2397, 2490, 2665, 2876, 3021, 3182, 3383, 3547, 3604 };      //G
            //N1_Gamma_Index[2] = new int[24] { 0, 823, 942, 1066, 1286, 1446, 1557, 1661, 1812, 1933, 2041, 2198, 2382, 2560, 2685, 2791, 2882, 3053, 3251, 3388, 3543, 3736, 3891, 3946 };  //B  

            N1_Gamma_Index[0] = new int[24] {Convert.ToInt16(num_ILI8818_R0.Value), Convert.ToInt16(num_ILI8818_R1.Value), Convert.ToInt16(num_ILI8818_R2.Value), Convert.ToInt16(num_ILI8818_R3.Value), Convert.ToInt16(num_ILI8818_R4.Value), Convert.ToInt16(num_ILI8818_R5.Value), Convert.ToInt16(num_ILI8818_R6.Value), Convert.ToInt16(num_ILI8818_R7.Value), Convert.ToInt16(num_ILI8818_R8.Value), Convert.ToInt16(num_ILI8818_R9.Value), Convert.ToInt16(num_ILI8818_R10.Value), Convert.ToInt16(num_ILI8818_R11.Value),
                                              Convert.ToInt16(num_ILI8818_R12.Value), Convert.ToInt16(num_ILI8818_R13.Value),Convert.ToInt16(num_ILI8818_R14.Value), Convert.ToInt16(num_ILI8818_R15.Value), Convert.ToInt16(num_ILI8818_R16.Value), Convert.ToInt16(num_ILI8818_R17.Value), Convert.ToInt16(num_ILI8818_R18.Value), Convert.ToInt16(num_ILI8818_R19.Value), Convert.ToInt16(num_ILI8818_R20.Value), Convert.ToInt16(num_ILI8818_R21.Value), Convert.ToInt16(num_ILI8818_R22.Value), Convert.ToInt16(num_ILI8818_R23.Value) };
            N1_Gamma_Index[1] = new int[24] {Convert.ToInt16(num_ILI8818_G0.Value), Convert.ToInt16(num_ILI8818_G1.Value), Convert.ToInt16(num_ILI8818_G2.Value), Convert.ToInt16(num_ILI8818_G3.Value), Convert.ToInt16(num_ILI8818_G4.Value), Convert.ToInt16(num_ILI8818_G5.Value), Convert.ToInt16(num_ILI8818_G6.Value), Convert.ToInt16(num_ILI8818_G7.Value), Convert.ToInt16(num_ILI8818_G8.Value), Convert.ToInt16(num_ILI8818_G9.Value), Convert.ToInt16(num_ILI8818_G10.Value), Convert.ToInt16(num_ILI8818_G11.Value),
                                              Convert.ToInt16(num_ILI8818_G12.Value), Convert.ToInt16(num_ILI8818_G13.Value),Convert.ToInt16(num_ILI8818_G14.Value), Convert.ToInt16(num_ILI8818_G15.Value), Convert.ToInt16(num_ILI8818_G16.Value), Convert.ToInt16(num_ILI8818_G17.Value), Convert.ToInt16(num_ILI8818_G18.Value), Convert.ToInt16(num_ILI8818_G19.Value), Convert.ToInt16(num_ILI8818_G20.Value), Convert.ToInt16(num_ILI8818_G21.Value), Convert.ToInt16(num_ILI8818_G22.Value), Convert.ToInt16(num_ILI8818_G23.Value) };                                                                                                                                                                             //N1_GammaIndex[0][Gamma_Point_Num]為R的GAMMA INDEX, N1_GammaIndex[1][Gamma_Point_Num]為G的GAMMA INDEX,N1_GammaIndex[2][Gamma_Point_Num]為B的GAMMA INDEX

            N1_Gamma_Index[2] = new int[24] {Convert.ToInt16(num_ILI8818_B0.Value), Convert.ToInt16(num_ILI8818_B1.Value), Convert.ToInt16(num_ILI8818_B2.Value), Convert.ToInt16(num_ILI8818_B3.Value), Convert.ToInt16(num_ILI8818_B4.Value), Convert.ToInt16(num_ILI8818_B5.Value), Convert.ToInt16(num_ILI8818_B6.Value), Convert.ToInt16(num_ILI8818_B7.Value), Convert.ToInt16(num_ILI8818_B8.Value), Convert.ToInt16(num_ILI8818_B9.Value), Convert.ToInt16(num_ILI8818_B10.Value), Convert.ToInt16(num_ILI8818_B11.Value),
                                              Convert.ToInt16(num_ILI8818_B12.Value), Convert.ToInt16(num_ILI8818_B13.Value),Convert.ToInt16(num_ILI8818_B14.Value), Convert.ToInt16(num_ILI8818_B15.Value), Convert.ToInt16(num_ILI8818_B16.Value), Convert.ToInt16(num_ILI8818_B17.Value), Convert.ToInt16(num_ILI8818_B18.Value), Convert.ToInt16(num_ILI8818_B19.Value), Convert.ToInt16(num_ILI8818_B20.Value), Convert.ToInt16(num_ILI8818_B21.Value), Convert.ToInt16(num_ILI8818_B22.Value), Convert.ToInt16(num_ILI8818_B23.Value) };


            //int N2_DBV = 281; // read register : P9_AD_AE
            int N2_DBV = Convert.ToInt16(txt_Calc.Text);

            //===========From initial code=============//

            int i, j, k;
            double[] N2_Table = new double[24];
            double Ratio = Math.Pow(Convert.ToDouble(N2_DBV / 1023.0), 1 / 2.2);
            int[][] N2_Gamma_Value = new int[3][];
            N2_Gamma_Value[0] = new int[24];
            N2_Gamma_Value[1] = new int[24];
            N2_Gamma_Value[2] = new int[24];

            for (i = 0; i < Gamma_Point_Num; i++)
            {
                N2_Table[i] = N1_GammaPoint[i] * Ratio;
            }


            for (i = 0; i < Gamma_Point_Num; i++)
            {
                for (j = 0; j < (Gamma_Point_Num - 1); j++)
                {
                    if (N2_Table[i] >= N1_GammaPoint[j] && N2_Table[i] <= N1_GammaPoint[j + 1])
                    {
                        for (k = 0; k < 3; k++)
                        {
                            N2_Gamma_Value[k][i] = Convert.ToInt16(((N2_Table[i] - N1_GammaPoint[j]) * N1_Gamma_Index[k][j + 1] + (N1_GammaPoint[j + 1] - N2_Table[i]) * N1_Gamma_Index[k][j]) / (N1_GammaPoint[j + 1] - (float)N1_GammaPoint[j]));
                        }
                        break;
                    }
                }
            }
            {
                {
                    num_ILI8818_R0.Value = Convert.ToDecimal(N2_Gamma_Value[0][0]);
                    num_ILI8818_R1.Value = Convert.ToDecimal(N2_Gamma_Value[0][1]);
                    num_ILI8818_R2.Value = Convert.ToDecimal(N2_Gamma_Value[0][2]);
                    num_ILI8818_R3.Value = Convert.ToDecimal(N2_Gamma_Value[0][3]);
                    num_ILI8818_R4.Value = Convert.ToDecimal(N2_Gamma_Value[0][4]);
                    num_ILI8818_R5.Value = Convert.ToDecimal(N2_Gamma_Value[0][5]);
                    num_ILI8818_R6.Value = Convert.ToDecimal(N2_Gamma_Value[0][6]);
                    num_ILI8818_R7.Value = Convert.ToDecimal(N2_Gamma_Value[0][7]);
                    num_ILI8818_R8.Value = Convert.ToDecimal(N2_Gamma_Value[0][8]);
                    num_ILI8818_R9.Value = Convert.ToDecimal(N2_Gamma_Value[0][9]);
                    num_ILI8818_R10.Value = Convert.ToDecimal(N2_Gamma_Value[0][10]);
                    num_ILI8818_R11.Value = Convert.ToDecimal(N2_Gamma_Value[0][11]);

                    num_ILI8818_R12.Value = Convert.ToDecimal(N2_Gamma_Value[0][12]);
                    num_ILI8818_R13.Value = Convert.ToDecimal(N2_Gamma_Value[0][13]);
                    num_ILI8818_R14.Value = Convert.ToDecimal(N2_Gamma_Value[0][14]);
                    num_ILI8818_R15.Value = Convert.ToDecimal(N2_Gamma_Value[0][15]);
                    num_ILI8818_R16.Value = Convert.ToDecimal(N2_Gamma_Value[0][16]);
                    num_ILI8818_R17.Value = Convert.ToDecimal(N2_Gamma_Value[0][17]);
                    num_ILI8818_R18.Value = Convert.ToDecimal(N2_Gamma_Value[0][18]);
                    num_ILI8818_R19.Value = Convert.ToDecimal(N2_Gamma_Value[0][19]);
                    num_ILI8818_R20.Value = Convert.ToDecimal(N2_Gamma_Value[0][20]);
                    num_ILI8818_R21.Value = Convert.ToDecimal(N2_Gamma_Value[0][21]);
                    num_ILI8818_R22.Value = Convert.ToDecimal(N2_Gamma_Value[0][22]);
                    num_ILI8818_R23.Value = Convert.ToDecimal(N2_Gamma_Value[0][23]);
                }
            }
            {
                num_ILI8818_G0.Value = Convert.ToDecimal(N2_Gamma_Value[1][0]);
                num_ILI8818_G1.Value = Convert.ToDecimal(N2_Gamma_Value[1][1]);
                num_ILI8818_G2.Value = Convert.ToDecimal(N2_Gamma_Value[1][2]);
                num_ILI8818_G3.Value = Convert.ToDecimal(N2_Gamma_Value[1][3]);
                num_ILI8818_G4.Value = Convert.ToDecimal(N2_Gamma_Value[1][4]);
                num_ILI8818_G5.Value = Convert.ToDecimal(N2_Gamma_Value[1][5]);
                num_ILI8818_G6.Value = Convert.ToDecimal(N2_Gamma_Value[1][6]);
                num_ILI8818_G7.Value = Convert.ToDecimal(N2_Gamma_Value[1][7]);
                num_ILI8818_G8.Value = Convert.ToDecimal(N2_Gamma_Value[1][8]);
                num_ILI8818_G9.Value = Convert.ToDecimal(N2_Gamma_Value[1][9]);
                num_ILI8818_G10.Value = Convert.ToDecimal(N2_Gamma_Value[1][10]);
                num_ILI8818_G11.Value = Convert.ToDecimal(N2_Gamma_Value[1][11]);

                num_ILI8818_G12.Value = Convert.ToDecimal(N2_Gamma_Value[1][12]);
                num_ILI8818_G13.Value = Convert.ToDecimal(N2_Gamma_Value[1][13]);
                num_ILI8818_G14.Value = Convert.ToDecimal(N2_Gamma_Value[1][14]);
                num_ILI8818_G15.Value = Convert.ToDecimal(N2_Gamma_Value[1][15]);
                num_ILI8818_G16.Value = Convert.ToDecimal(N2_Gamma_Value[1][16]);
                num_ILI8818_G17.Value = Convert.ToDecimal(N2_Gamma_Value[1][17]);
                num_ILI8818_G18.Value = Convert.ToDecimal(N2_Gamma_Value[1][18]);
                num_ILI8818_G19.Value = Convert.ToDecimal(N2_Gamma_Value[1][19]);
                num_ILI8818_G20.Value = Convert.ToDecimal(N2_Gamma_Value[1][20]);
                num_ILI8818_G21.Value = Convert.ToDecimal(N2_Gamma_Value[1][21]);
                num_ILI8818_G22.Value = Convert.ToDecimal(N2_Gamma_Value[1][22]);
                num_ILI8818_G23.Value = Convert.ToDecimal(N2_Gamma_Value[1][23]);
            }
            {
                num_ILI8818_B0.Value = Convert.ToDecimal(N2_Gamma_Value[2][0]);
                num_ILI8818_B1.Value = Convert.ToDecimal(N2_Gamma_Value[2][1]);
                num_ILI8818_B2.Value = Convert.ToDecimal(N2_Gamma_Value[2][2]);
                num_ILI8818_B3.Value = Convert.ToDecimal(N2_Gamma_Value[2][3]);
                num_ILI8818_B4.Value = Convert.ToDecimal(N2_Gamma_Value[2][4]);
                num_ILI8818_B5.Value = Convert.ToDecimal(N2_Gamma_Value[2][5]);
                num_ILI8818_B6.Value = Convert.ToDecimal(N2_Gamma_Value[2][6]);
                num_ILI8818_B7.Value = Convert.ToDecimal(N2_Gamma_Value[2][7]);
                num_ILI8818_B8.Value = Convert.ToDecimal(N2_Gamma_Value[2][8]);
                num_ILI8818_B9.Value = Convert.ToDecimal(N2_Gamma_Value[2][9]);
                num_ILI8818_B10.Value = Convert.ToDecimal(N2_Gamma_Value[2][10]);
                num_ILI8818_B11.Value = Convert.ToDecimal(N2_Gamma_Value[2][11]);

                num_ILI8818_B12.Value = Convert.ToDecimal(N2_Gamma_Value[2][12]);
                num_ILI8818_B13.Value = Convert.ToDecimal(N2_Gamma_Value[2][13]);
                num_ILI8818_B14.Value = Convert.ToDecimal(N2_Gamma_Value[2][14]);
                num_ILI8818_B15.Value = Convert.ToDecimal(N2_Gamma_Value[2][15]);
                num_ILI8818_B16.Value = Convert.ToDecimal(N2_Gamma_Value[2][16]);
                num_ILI8818_B17.Value = Convert.ToDecimal(N2_Gamma_Value[2][17]);
                num_ILI8818_B18.Value = Convert.ToDecimal(N2_Gamma_Value[2][18]);
                num_ILI8818_B19.Value = Convert.ToDecimal(N2_Gamma_Value[2][19]);
                num_ILI8818_B20.Value = Convert.ToDecimal(N2_Gamma_Value[2][20]);
                num_ILI8818_B21.Value = Convert.ToDecimal(N2_Gamma_Value[2][21]);
                num_ILI8818_B22.Value = Convert.ToDecimal(N2_Gamma_Value[2][22]);
                num_ILI8818_B23.Value = Convert.ToDecimal(N2_Gamma_Value[2][23]);
            }

        }


        //一键magic
        private void button_magic_Click(object sender, EventArgs e)
        {
            decimal[] magic_tempR = new decimal[13];
            decimal[] magic_tempG = new decimal[13];
            decimal[] magic_tempB = new decimal[13];
            //R 0-65
            magic_tempR[0] = num_ILI8818_R0.Value;      //0
            magic_tempR[1] = num_ILI8818_R1.Value;
            magic_tempR[2] = num_ILI8818_R2.Value;
            magic_tempR[3] = num_ILI8818_R3.Value;
            magic_tempR[4] = num_ILI8818_R4.Value;
            magic_tempR[5] = num_ILI8818_R5.Value;
            magic_tempR[6] = num_ILI8818_R6.Value;
            magic_tempR[7] = num_ILI8818_R7.Value;
            magic_tempR[8] = num_ILI8818_R8.Value;
            magic_tempR[9] = num_ILI8818_R9.Value;
            magic_tempR[10] = num_ILI8818_R10.Value;
            magic_tempR[11] = num_ILI8818_R11.Value;
            magic_tempR[12] = num_ILI8818_R12.Value;         //65
            //G 0-65
            magic_tempG[0] = num_ILI8818_G0.Value;      //0
            magic_tempG[1] = num_ILI8818_G1.Value;
            magic_tempG[2] = num_ILI8818_G2.Value;
            magic_tempG[3] = num_ILI8818_G3.Value;
            magic_tempG[4] = num_ILI8818_G4.Value;
            magic_tempG[5] = num_ILI8818_G5.Value;
            magic_tempG[6] = num_ILI8818_G6.Value;
            magic_tempG[7] = num_ILI8818_G7.Value;
            magic_tempG[8] = num_ILI8818_G8.Value;
            magic_tempG[9] = num_ILI8818_G9.Value;
            magic_tempG[10] = num_ILI8818_G10.Value;
            magic_tempG[11] = num_ILI8818_G11.Value;
            magic_tempG[12] = num_ILI8818_G12.Value;         //65
            //B 0-65
            magic_tempB[0] = num_ILI8818_B0.Value;      //0
            magic_tempB[1] = num_ILI8818_B1.Value;
            magic_tempB[2] = num_ILI8818_B2.Value;
            magic_tempB[3] = num_ILI8818_B3.Value;
            magic_tempB[4] = num_ILI8818_B4.Value;
            magic_tempB[5] = num_ILI8818_B5.Value;
            magic_tempB[6] = num_ILI8818_B6.Value;
            magic_tempB[7] = num_ILI8818_B7.Value;
            magic_tempB[8] = num_ILI8818_B8.Value;
            magic_tempB[9] = num_ILI8818_B9.Value;
            magic_tempB[10] = num_ILI8818_B10.Value;
            magic_tempB[11] = num_ILI8818_B11.Value;
            magic_tempB[12] = num_ILI8818_B12.Value;         //65

            //gamma2 转换到 gamma3
            //R
            num_ILI8818_R0.Value = Convert.ToInt32(magic_tempR[0]);
            num_ILI8818_R1.Value = Convert.ToInt32(magic_tempR[1] * Convert.ToDecimal(0.2284) + magic_tempR[0] * Convert.ToDecimal(0.7716));
            num_ILI8818_R2.Value = Convert.ToInt32(magic_tempR[1] * Convert.ToDecimal(0.6853) + magic_tempR[0] * Convert.ToDecimal(0.3147));
            num_ILI8818_R3.Value = Convert.ToInt32(magic_tempR[2] * Convert.ToDecimal(0.0711) + magic_tempR[1] * Convert.ToDecimal(0.9289));
            num_ILI8818_R4.Value = Convert.ToInt32(magic_tempR[2] * Convert.ToDecimal(0.5279) + magic_tempR[1] * Convert.ToDecimal(0.4721));
            num_ILI8818_R5.Value = Convert.ToInt32(magic_tempR[2] * Convert.ToDecimal(0.9847) + magic_tempR[1] * Convert.ToDecimal(0.0153));
            num_ILI8818_R6.Value = Convert.ToInt32(magic_tempR[3] * Convert.ToDecimal(0.4416) + magic_tempR[2] * Convert.ToDecimal(0.5584));
            num_ILI8818_R7.Value = Convert.ToInt32(magic_tempR[4] * Convert.ToDecimal(0.0063) + magic_tempR[3] * Convert.ToDecimal(0.9937));
            num_ILI8818_R8.Value = Convert.ToInt32(magic_tempR[4] * Convert.ToDecimal(0.4061) + magic_tempR[3] * Convert.ToDecimal(0.5939));
            num_ILI8818_R9.Value = Convert.ToInt32(magic_tempR[4] * Convert.ToDecimal(0.7487) + magic_tempR[3] * Convert.ToDecimal(0.2513));
            num_ILI8818_R10.Value = Convert.ToInt32(magic_tempR[5] * Convert.ToDecimal(0.0913) + magic_tempR[4] * Convert.ToDecimal(0.9087));
            num_ILI8818_R11.Value = Convert.ToInt32(magic_tempR[5] * Convert.ToDecimal(0.6624) + magic_tempR[4] * Convert.ToDecimal(0.3376));
            num_ILI8818_R12.Value = Convert.ToInt32(magic_tempR[6] * Convert.ToDecimal(0.4619) + magic_tempR[5] * Convert.ToDecimal(0.5381));
            num_ILI8818_R13.Value = Convert.ToInt32(magic_tempR[7] * Convert.ToDecimal(0.3004) + magic_tempR[6] * Convert.ToDecimal(0.6996));
            num_ILI8818_R14.Value = Convert.ToInt32(magic_tempR[7] * Convert.ToDecimal(0.8486) + magic_tempR[6] * Convert.ToDecimal(0.1514));
            num_ILI8818_R15.Value = Convert.ToInt32(magic_tempR[8] * Convert.ToDecimal(0.2508) + magic_tempR[7] * Convert.ToDecimal(0.7492));
            num_ILI8818_R16.Value = Convert.ToInt32(magic_tempR[8] * Convert.ToDecimal(0.5772) + magic_tempR[7] * Convert.ToDecimal(0.4228));
            num_ILI8818_R17.Value = Convert.ToInt32(magic_tempR[9] * Convert.ToDecimal(0.2681) + magic_tempR[8] * Convert.ToDecimal(0.7319));
            num_ILI8818_R18.Value = Convert.ToInt32(magic_tempR[10] * Convert.ToDecimal(0.2198) + magic_tempR[9] * Convert.ToDecimal(0.7802));
            num_ILI8818_R19.Value = Convert.ToInt32(magic_tempR[10] * Convert.ToDecimal(0.9051) + magic_tempR[9] * Convert.ToDecimal(0.0949));
            num_ILI8818_R20.Value = Convert.ToInt32(magic_tempR[11] * Convert.ToDecimal(0.4228) + magic_tempR[10] * Convert.ToDecimal(0.5772));
            num_ILI8818_R21.Value = Convert.ToInt32(magic_tempR[12] * Convert.ToDecimal(0.0282) + magic_tempR[11] * Convert.ToDecimal(0.9718));
            num_ILI8818_R22.Value = Convert.ToInt32(magic_tempR[12] * Convert.ToDecimal(0.3872) + magic_tempR[11] * Convert.ToDecimal(0.6128));
            num_ILI8818_R23.Value = Convert.ToInt32(magic_tempR[12] * Convert.ToDecimal(0.5177) + magic_tempR[11] * Convert.ToDecimal(0.4823));

            //GGGGGG
            num_ILI8818_G0.Value = Convert.ToInt32(magic_tempG[0]);
            num_ILI8818_G1.Value = Convert.ToInt32(magic_tempG[1] * Convert.ToDecimal(0.2284) + magic_tempG[0] * Convert.ToDecimal(0.7716));
            num_ILI8818_G2.Value = Convert.ToInt32(magic_tempG[1] * Convert.ToDecimal(0.6853) + magic_tempG[0] * Convert.ToDecimal(0.3147));
            num_ILI8818_G3.Value = Convert.ToInt32(magic_tempG[2] * Convert.ToDecimal(0.0711) + magic_tempG[1] * Convert.ToDecimal(0.9289));
            num_ILI8818_G4.Value = Convert.ToInt32(magic_tempG[2] * Convert.ToDecimal(0.5279) + magic_tempG[1] * Convert.ToDecimal(0.4721));
            num_ILI8818_G5.Value = Convert.ToInt32(magic_tempG[2] * Convert.ToDecimal(0.9847) + magic_tempG[1] * Convert.ToDecimal(0.0153));
            num_ILI8818_G6.Value = Convert.ToInt32(magic_tempG[3] * Convert.ToDecimal(0.4416) + magic_tempG[2] * Convert.ToDecimal(0.5584));
            num_ILI8818_G7.Value = Convert.ToInt32(magic_tempG[4] * Convert.ToDecimal(0.0063) + magic_tempG[3] * Convert.ToDecimal(0.9937));
            num_ILI8818_G8.Value = Convert.ToInt32(magic_tempG[4] * Convert.ToDecimal(0.4061) + magic_tempG[3] * Convert.ToDecimal(0.5939));
            num_ILI8818_G9.Value = Convert.ToInt32(magic_tempG[4] * Convert.ToDecimal(0.7487) + magic_tempG[3] * Convert.ToDecimal(0.2513));
            num_ILI8818_G10.Value = Convert.ToInt32(magic_tempG[5] * Convert.ToDecimal(0.0913) + magic_tempG[4] * Convert.ToDecimal(0.9087));
            num_ILI8818_G11.Value = Convert.ToInt32(magic_tempG[5] * Convert.ToDecimal(0.6624) + magic_tempG[4] * Convert.ToDecimal(0.3376));
            num_ILI8818_G12.Value = Convert.ToInt32(magic_tempG[6] * Convert.ToDecimal(0.4619) + magic_tempG[5] * Convert.ToDecimal(0.5381));
            num_ILI8818_G13.Value = Convert.ToInt32(magic_tempG[7] * Convert.ToDecimal(0.3004) + magic_tempG[6] * Convert.ToDecimal(0.6996));
            num_ILI8818_G14.Value = Convert.ToInt32(magic_tempG[7] * Convert.ToDecimal(0.8486) + magic_tempG[6] * Convert.ToDecimal(0.1514));
            num_ILI8818_G15.Value = Convert.ToInt32(magic_tempG[8] * Convert.ToDecimal(0.2508) + magic_tempG[7] * Convert.ToDecimal(0.7492));
            num_ILI8818_G16.Value = Convert.ToInt32(magic_tempG[8] * Convert.ToDecimal(0.5772) + magic_tempG[7] * Convert.ToDecimal(0.4228));
            num_ILI8818_G17.Value = Convert.ToInt32(magic_tempG[9] * Convert.ToDecimal(0.2681) + magic_tempG[8] * Convert.ToDecimal(0.7319));
            num_ILI8818_G18.Value = Convert.ToInt32(magic_tempG[10] * Convert.ToDecimal(0.2198) + magic_tempG[9] * Convert.ToDecimal(0.7802));
            num_ILI8818_G19.Value = Convert.ToInt32(magic_tempG[10] * Convert.ToDecimal(0.9051) + magic_tempG[9] * Convert.ToDecimal(0.0949));
            num_ILI8818_G20.Value = Convert.ToInt32(magic_tempG[11] * Convert.ToDecimal(0.4228) + magic_tempG[10] * Convert.ToDecimal(0.5772));
            num_ILI8818_G21.Value = Convert.ToInt32(magic_tempG[12] * Convert.ToDecimal(0.0282) + magic_tempG[11] * Convert.ToDecimal(0.9718));
            num_ILI8818_G22.Value = Convert.ToInt32(magic_tempG[12] * Convert.ToDecimal(0.3872) + magic_tempG[11] * Convert.ToDecimal(0.6128));
            num_ILI8818_G23.Value = Convert.ToInt32(magic_tempG[12] * Convert.ToDecimal(0.5177) + magic_tempG[11] * Convert.ToDecimal(0.4823));

            //BBBBBBBB
            num_ILI8818_B0.Value = Convert.ToInt32(magic_tempB[0]);
            num_ILI8818_B1.Value = Convert.ToInt32(magic_tempB[1] * Convert.ToDecimal(0.2284) + magic_tempB[0] * Convert.ToDecimal(0.7716));
            num_ILI8818_B2.Value = Convert.ToInt32(magic_tempB[1] * Convert.ToDecimal(0.6853) + magic_tempB[0] * Convert.ToDecimal(0.3147));
            num_ILI8818_B3.Value = Convert.ToInt32(magic_tempB[2] * Convert.ToDecimal(0.0711) + magic_tempB[1] * Convert.ToDecimal(0.9289));
            num_ILI8818_B4.Value = Convert.ToInt32(magic_tempB[2] * Convert.ToDecimal(0.5279) + magic_tempB[1] * Convert.ToDecimal(0.4721));
            num_ILI8818_B5.Value = Convert.ToInt32(magic_tempB[2] * Convert.ToDecimal(0.9847) + magic_tempB[1] * Convert.ToDecimal(0.0153));
            num_ILI8818_B6.Value = Convert.ToInt32(magic_tempB[3] * Convert.ToDecimal(0.4416) + magic_tempB[2] * Convert.ToDecimal(0.5584));
            num_ILI8818_B7.Value = Convert.ToInt32(magic_tempB[4] * Convert.ToDecimal(0.0063) + magic_tempB[3] * Convert.ToDecimal(0.9937));
            num_ILI8818_B8.Value = Convert.ToInt32(magic_tempB[4] * Convert.ToDecimal(0.4061) + magic_tempB[3] * Convert.ToDecimal(0.5939));
            num_ILI8818_B9.Value = Convert.ToInt32(magic_tempB[4] * Convert.ToDecimal(0.7487) + magic_tempB[3] * Convert.ToDecimal(0.2513));
            num_ILI8818_B10.Value = Convert.ToInt32(magic_tempB[5] * Convert.ToDecimal(0.0913) + magic_tempB[4] * Convert.ToDecimal(0.9087));
            num_ILI8818_B11.Value = Convert.ToInt32(magic_tempB[5] * Convert.ToDecimal(0.6624) + magic_tempB[4] * Convert.ToDecimal(0.3376));
            num_ILI8818_B12.Value = Convert.ToInt32(magic_tempB[6] * Convert.ToDecimal(0.4619) + magic_tempB[5] * Convert.ToDecimal(0.5381));
            num_ILI8818_B13.Value = Convert.ToInt32(magic_tempB[7] * Convert.ToDecimal(0.3004) + magic_tempB[6] * Convert.ToDecimal(0.6996));
            num_ILI8818_B14.Value = Convert.ToInt32(magic_tempB[7] * Convert.ToDecimal(0.8486) + magic_tempB[6] * Convert.ToDecimal(0.1514));
            num_ILI8818_B15.Value = Convert.ToInt32(magic_tempB[8] * Convert.ToDecimal(0.2508) + magic_tempB[7] * Convert.ToDecimal(0.7492));
            num_ILI8818_B16.Value = Convert.ToInt32(magic_tempB[8] * Convert.ToDecimal(0.5772) + magic_tempB[7] * Convert.ToDecimal(0.4228));
            num_ILI8818_B17.Value = Convert.ToInt32(magic_tempB[9] * Convert.ToDecimal(0.2681) + magic_tempB[8] * Convert.ToDecimal(0.7319));
            num_ILI8818_B18.Value = Convert.ToInt32(magic_tempB[10] * Convert.ToDecimal(0.2198) + magic_tempB[9] * Convert.ToDecimal(0.7802));
            num_ILI8818_B19.Value = Convert.ToInt32(magic_tempB[10] * Convert.ToDecimal(0.9051) + magic_tempB[9] * Convert.ToDecimal(0.0949));
            num_ILI8818_B20.Value = Convert.ToInt32(magic_tempB[11] * Convert.ToDecimal(0.4228) + magic_tempB[10] * Convert.ToDecimal(0.5772));
            num_ILI8818_B21.Value = Convert.ToInt32(magic_tempB[12] * Convert.ToDecimal(0.0282) + magic_tempB[11] * Convert.ToDecimal(0.9718));
            num_ILI8818_B22.Value = Convert.ToInt32(magic_tempB[12] * Convert.ToDecimal(0.3872) + magic_tempB[11] * Convert.ToDecimal(0.6128));
            num_ILI8818_B23.Value = Convert.ToInt32(magic_tempB[12] * Convert.ToDecimal(0.5177) + magic_tempB[11] * Convert.ToDecimal(0.4823));
        }

        //检测灰阶反转问题
        private void button_checkdata_Click(object sender, EventArgs e)
        {
            int int_tempR0 = Convert.ToInt32(num_ILI8818_R0.Value);
            int int_tempR1 = Convert.ToInt32(num_ILI8818_R1.Value);
            int int_tempR2 = Convert.ToInt32(num_ILI8818_R2.Value);
            int int_tempR3 = Convert.ToInt32(num_ILI8818_R3.Value);
            int int_tempR4 = Convert.ToInt32(num_ILI8818_R4.Value);
            int int_tempR5 = Convert.ToInt32(num_ILI8818_R5.Value);
            int int_tempR6 = Convert.ToInt32(num_ILI8818_R6.Value);
            int int_tempR7 = Convert.ToInt32(num_ILI8818_R7.Value);
            int int_tempR8 = Convert.ToInt32(num_ILI8818_R8.Value);
            int int_tempR9 = Convert.ToInt32(num_ILI8818_R9.Value);
            int int_tempR10 = Convert.ToInt32(num_ILI8818_R10.Value);
            int int_tempR11 = Convert.ToInt32(num_ILI8818_R11.Value);
            int int_tempR12 = Convert.ToInt32(num_ILI8818_R12.Value);
            int int_tempR13 = Convert.ToInt32(num_ILI8818_R13.Value);
            int int_tempR14 = Convert.ToInt32(num_ILI8818_R14.Value);
            int int_tempR15 = Convert.ToInt32(num_ILI8818_R15.Value);
            int int_tempR16 = Convert.ToInt32(num_ILI8818_R16.Value);
            int int_tempR17 = Convert.ToInt32(num_ILI8818_R17.Value);
            int int_tempR18 = Convert.ToInt32(num_ILI8818_R18.Value);
            int int_tempR19 = Convert.ToInt32(num_ILI8818_R19.Value);
            int int_tempR20 = Convert.ToInt32(num_ILI8818_R20.Value);
            int int_tempR21 = Convert.ToInt32(num_ILI8818_R21.Value);
            int int_tempR22 = Convert.ToInt32(num_ILI8818_R22.Value);
            int int_tempR23 = Convert.ToInt32(num_ILI8818_R23.Value);
            //G
            int int_tempG0 = Convert.ToInt32(num_ILI8818_G0.Value);
            int int_tempG1 = Convert.ToInt32(num_ILI8818_G1.Value);
            int int_tempG2 = Convert.ToInt32(num_ILI8818_G2.Value);
            int int_tempG3 = Convert.ToInt32(num_ILI8818_G3.Value);
            int int_tempG4 = Convert.ToInt32(num_ILI8818_G4.Value);
            int int_tempG5 = Convert.ToInt32(num_ILI8818_G5.Value);
            int int_tempG6 = Convert.ToInt32(num_ILI8818_G6.Value);
            int int_tempG7 = Convert.ToInt32(num_ILI8818_G7.Value);
            int int_tempG8 = Convert.ToInt32(num_ILI8818_G8.Value);
            int int_tempG9 = Convert.ToInt32(num_ILI8818_G9.Value);
            int int_tempG10 = Convert.ToInt32(num_ILI8818_G10.Value);
            int int_tempG11 = Convert.ToInt32(num_ILI8818_G11.Value);
            int int_tempG12 = Convert.ToInt32(num_ILI8818_G12.Value);
            int int_tempG13 = Convert.ToInt32(num_ILI8818_G13.Value);
            int int_tempG14 = Convert.ToInt32(num_ILI8818_G14.Value);
            int int_tempG15 = Convert.ToInt32(num_ILI8818_G15.Value);
            int int_tempG16 = Convert.ToInt32(num_ILI8818_G16.Value);
            int int_tempG17 = Convert.ToInt32(num_ILI8818_G17.Value);
            int int_tempG18 = Convert.ToInt32(num_ILI8818_G18.Value);
            int int_tempG19 = Convert.ToInt32(num_ILI8818_G19.Value);
            int int_tempG20 = Convert.ToInt32(num_ILI8818_G20.Value);
            int int_tempG21 = Convert.ToInt32(num_ILI8818_G21.Value);
            int int_tempG22 = Convert.ToInt32(num_ILI8818_G22.Value);
            int int_tempG23 = Convert.ToInt32(num_ILI8818_G23.Value);
            //BBBBBBBB
            int int_tempB0 = Convert.ToInt32(num_ILI8818_B0.Value);
            int int_tempB1 = Convert.ToInt32(num_ILI8818_B1.Value);
            int int_tempB2 = Convert.ToInt32(num_ILI8818_B2.Value);
            int int_tempB3 = Convert.ToInt32(num_ILI8818_B3.Value);
            int int_tempB4 = Convert.ToInt32(num_ILI8818_B4.Value);
            int int_tempB5 = Convert.ToInt32(num_ILI8818_B5.Value);
            int int_tempB6 = Convert.ToInt32(num_ILI8818_B6.Value);
            int int_tempB7 = Convert.ToInt32(num_ILI8818_B7.Value);
            int int_tempB8 = Convert.ToInt32(num_ILI8818_B8.Value);
            int int_tempB9 = Convert.ToInt32(num_ILI8818_B9.Value);
            int int_tempB10 = Convert.ToInt32(num_ILI8818_B10.Value);
            int int_tempB11 = Convert.ToInt32(num_ILI8818_B11.Value);
            int int_tempB12 = Convert.ToInt32(num_ILI8818_B12.Value);
            int int_tempB13 = Convert.ToInt32(num_ILI8818_B13.Value);
            int int_tempB14 = Convert.ToInt32(num_ILI8818_B14.Value);
            int int_tempB15 = Convert.ToInt32(num_ILI8818_B15.Value);
            int int_tempB16 = Convert.ToInt32(num_ILI8818_B16.Value);
            int int_tempB17 = Convert.ToInt32(num_ILI8818_B17.Value);
            int int_tempB18 = Convert.ToInt32(num_ILI8818_B18.Value);
            int int_tempB19 = Convert.ToInt32(num_ILI8818_B19.Value);
            int int_tempB20 = Convert.ToInt32(num_ILI8818_B20.Value);
            int int_tempB21 = Convert.ToInt32(num_ILI8818_B21.Value);
            int int_tempB22 = Convert.ToInt32(num_ILI8818_B22.Value);
            int int_tempB23 = Convert.ToInt32(num_ILI8818_B23.Value);

            //xiu cao zuo le
            int[] inttempRRR =
            {
                int_tempR0, int_tempR1, int_tempR2, int_tempR3, int_tempR4, int_tempR5, int_tempR6, int_tempR7, int_tempR8,
                int_tempR9,int_tempR10,int_tempR11,int_tempR12,int_tempR13,int_tempR14,int_tempR15,int_tempR16,int_tempR17,
                int_tempR18,int_tempR19,int_tempR20,int_tempR21,int_tempR22,int_tempR23
            };
            int[] inttempGGG =
            {
                int_tempG0, int_tempG1, int_tempG2, int_tempG3, int_tempG4, int_tempG5, int_tempG6, int_tempG7, int_tempG8,
                int_tempG9,int_tempG10,int_tempG11,int_tempG12,int_tempG13,int_tempG14,int_tempG15,int_tempG16,int_tempG17,
                int_tempG18,int_tempG19,int_tempG20,int_tempG21,int_tempG22,int_tempG23
            };
            int[] inttempBBB =
            {
                int_tempB0, int_tempB1, int_tempB2, int_tempB3, int_tempB4, int_tempB5, int_tempB6, int_tempB7, int_tempB8,
                int_tempB9,int_tempB10,int_tempB11,int_tempB12,int_tempB13,int_tempB14,int_tempB15,int_tempB16,int_tempB17,
                int_tempB18,int_tempB19,int_tempB20,int_tempB21,int_tempB22,int_tempB23
            };
            for (int i = 1; i < 24; i++)
            {
                if (inttempRRR[i - 1] > 0)
                {
                    if (inttempRRR[i] <= inttempRRR[i - 1])
                    {
                        frmHelp.textBox1.Text += "R:" + i.ToString() + "_值位:" + String.Format("{0:X}", inttempRRR[i]) + "\r\n";
                    }
                }

                if (inttempGGG[i - 1] > 0)
                {
                    if (inttempGGG[i] <= inttempGGG[i - 1])
                    {
                        frmHelp.textBox1.Text += "G:" + i.ToString() + "_值位:" + String.Format("{0:X}", inttempGGG[i]) + "\r\n";
                    }
                }

                if (inttempBBB[i - 1] > 0)
                {
                    if (inttempBBB[i] <= inttempBBB[i - 1])
                    {
                        frmHelp.textBox1.Text += "B:" + i.ToString() + "_值位:" + String.Format("{0:X}", inttempBBB[i]) + "\r\n";
                    }
                }
            }

            frmHelp.textBox1.Text += "end \r\n";

        }


        public static void Delay(int milliSecond)
        {
            int start = Environment.TickCount;
            while (Math.Abs(Environment.TickCount - start) < milliSecond)//毫秒
            {
                Application.DoEvents();//可执行某无聊的操作
            }
        }

        string cmdstr = "";
        private void SetBlkPara(int G1, int G2, int G3, int X1, int X2, int X3, int X4)
        {
            string txtbaseClearOriginal;
            string txtMClearOriginal;

            int[] nGray = new int[3];
            int[,] nBox = new int[2, 2];
            int value;
            int[] nGrayBoxB = new int[3] { 0, 0, 0 };

            nGray[0] = G1 * 4;
            nGray[1] = G2 * 4;
            nGray[2] = G3 * 4;
            nBox[0, 0] = X1 / 4;
            nBox[0, 1] = X2;
            nBox[1, 0] = (X3 - (X3 % 4)) / 4;
            nBox[1, 1] = X4;

            /* BIST mode */
            //REGISTER,FF,3,78,38,02;
            cmdstr = "FF,78,38,02";

            /* BIST mode pattern selection */
            //REGISTER,28,1,00;
            //REGISTER,29,1,04;
            //REGISTER,2A,1,00;
            cmdstr = cmdstr + ";" + "28,00;29,04;2A,00";

            /* enable white box measurement in BIST mode */
            //REGISTER,ED,1,02;
            cmdstr = cmdstr + ";" + "ED,02";

            /* Set white box X/Y-axis diameter & RGB Gray inside/outside the white box */
            //REGISTER,E0,1,IntToHex((nBox[0,1] & 0x000000FF),2);
            //REGISTER,E1,1,IntToHex((nBox[1,1] & 0x000000FF),2);
            cmdstr = cmdstr + ";" + "E0" + "," + (nBox[0, 1] & 0x000000FF).ToString("X2");
            cmdstr = cmdstr + ";" + "E1" + "," + (nBox[1, 1] & 0x000000FF).ToString("X2");

            value = ((nBox[1, 1] & 0x0000FF00) >> 4) + ((nBox[0, 1] & 0x0000FF00) >> 8);
            //REGISTER,E2,1, IntToHex((value & 0x000000FF),2);
            cmdstr = cmdstr + ";" + "E2" + "," + (value & 0x000000FF).ToString("X2");

            //REGISTER,E3,1,IntToHex((nBox[0,0] & 0x000000FF),2);
            //REGISTER,E4,1,IntToHex((nBox[1,0] & 0x000000FF),2);
            cmdstr = cmdstr + ";" + "E3" + "," + (nBox[0, 0] & 0x000000FF).ToString("X2");
            cmdstr = cmdstr + ";" + "E4" + "," + (nBox[1, 0] & 0x000000FF).ToString("X2");

            value = ((nBox[1, 0] & 0x0000FF00) >> 2) + ((nBox[0, 0] & 0x0000FF00) >> 4) +
                   ((nGray[0] & 0x0000FF00) >> 6) + ((nGray[1] & 0x0000FF00) >> 8);
            //REGISTER,E5,1, IntToHex((value & 0x000000FF),2);
            cmdstr = cmdstr + ";" + "E5" + "," + (value & 0x000000FF).ToString("X2");

            value = ((nGray[2] & 0x0000FF00) >> 2) + ((nGrayBoxB[0] & 0x0000FF00) >> 4) +
                   ((nGrayBoxB[1] & 0x0000FF00) >> 6) + ((nGrayBoxB[2] & 0x0000FF00) >> 8);
            //REGISTER,E6,1, IntToHex((value & 0x000000FF),2);
            cmdstr = cmdstr + ";" + "E6" + "," + (value & 0x000000FF).ToString("X2");

            //REGISTER,E7,1,IntToHex((nGray[0] & 0x000000FF),2);
            //REGISTER,E8,1,IntToHex((nGray[1] & 0x000000FF),2);
            //REGISTER,E9,1,IntToHex((nGray[2] & 0x000000FF),2);
            //REGISTER,EA,1,IntToHex((nGrayBoxB[0] & 0x000000FF),2);
            //REGISTER,EB,1,IntToHex((nGrayBoxB[1] & 0x000000FF),2);
            //REGISTER,EC,1,IntToHex((nGrayBoxB[2] & 0x000000FF),2);
            cmdstr = cmdstr + ";" + "E7" + "," + (nGray[0] & 0x000000FF).ToString("X2");
            cmdstr = cmdstr + ";" + "E8" + "," + (nGray[1] & 0x000000FF).ToString("X2");
            cmdstr = cmdstr + ";" + "E9" + "," + (nGray[2] & 0x000000FF).ToString("X2");
            cmdstr = cmdstr + ";" + "EA" + "," + (nGrayBoxB[0] & 0x000000FF).ToString("X2");
            cmdstr = cmdstr + ";" + "EB" + "," + (nGrayBoxB[1] & 0x000000FF).ToString("X2");
            cmdstr = cmdstr + ";" + "EC" + "," + (nGrayBoxB[2] & 0x000000FF).ToString("X2");

            /* switch to page 0 */
            //REGISTER,FF,3,78,38,00;
            cmdstr = cmdstr + ";" + "FF,78,38,00";

            cmdstr = cmdstr.Replace(";", "\r\n");
            frmHelp.txtProcessDrivercode(cmdstr, out txtbaseClearOriginal, out txtMClearOriginal);
            //MainForm.SendCmd(0);    //低速写
            frmHelp.SendCmd(4);    //高速写

            Delay(500);
        }

        private void StartBistMode()
        {
            string txtbaseClearOriginal;
            string txtMClearOriginal;

            /* BIST mode */
            //REGISTER,FF,3,78,38,02;
            cmdstr = "FF,78,38,02";

            /* enable BIST mode */
            //REGISTER,2B,1,01;
            cmdstr = cmdstr + ";" + "2B,01";

            /* switch to page 0 */
            //REGISTER,FF,3,78,38,00;
            cmdstr = cmdstr + ";" + "FF,78,38,00";

            cmdstr = cmdstr.Replace(";", "\r\n");
            frmHelp.txtProcessDrivercode(cmdstr, out txtbaseClearOriginal, out txtMClearOriginal);
            //MainForm.SendCmd(0);    //低速写
            frmHelp.SendCmd(4);    //高速写

            Delay(200);
        }

        private void btnShowBlock_Click(object sender, EventArgs e)
        {
            int nHeight = int.Parse(txtResH.Text);
            int nWidth = int.Parse(txtResW.Text);
            int nNotchHeight = int.Parse(txtNotchH.Text);
            int blkImgSize = int.Parse(txtBlkImgSize.Text);

            int[] nBlkBoxSize = new int[4];

            nBlkBoxSize[0] = (nWidth - blkImgSize) / 2;
            nBlkBoxSize[1] = (nHeight - blkImgSize) / 2;
            nBlkBoxSize[2] = (nWidth + blkImgSize) / 2;
            nBlkBoxSize[3] = (nHeight + blkImgSize) / 2;

            if ((chkR.Checked) && (chkG.Checked) && (chkB.Checked))
            {
                SetBlkPara(255, 255, 255, nBlkBoxSize[0], nBlkBoxSize[1], nBlkBoxSize[2], nBlkBoxSize[3]);
            }
            else
            {
                if (chkR.Checked)
                {
                    SetBlkPara(255, 0, 0, nBlkBoxSize[0], nBlkBoxSize[1], nBlkBoxSize[2], nBlkBoxSize[3]);
                }
                else if (chkG.Checked)
                {
                    SetBlkPara(0, 255, 0, nBlkBoxSize[0], nBlkBoxSize[1], nBlkBoxSize[2], nBlkBoxSize[3]);
                }
                else if (chkB.Checked)
                {
                    SetBlkPara(0, 0, 255, nBlkBoxSize[0], nBlkBoxSize[1], nBlkBoxSize[2], nBlkBoxSize[3]);
                }
            }

            StartBistMode();
        }


        private void StopBistMode()
        {
            string txtbaseClearOriginal;
            string txtMClearOriginal;

            /* BIST mode */
            //REGISTER,FF,3,78,38,02;
            cmdstr = "FF,78,38,02";

            /* enable BIST mode */
            //REGISTER,2B,1,00; 
            cmdstr = cmdstr + ";" + "2B,00";

            /* switch to page 0 */
            //REGISTER,FF,3,78,38,00;
            cmdstr = cmdstr + ";" + "FF,78,38,00";

            cmdstr = cmdstr.Replace(";", "\r\n");
            frmHelp.txtProcessDrivercode(cmdstr, out txtbaseClearOriginal, out txtMClearOriginal);
            //MainForm.SendCmd(0);    //低速写
            frmHelp.SendCmd(4);    //高速写
        }

        private void btnExitBist_Click(object sender, EventArgs e)
        {
            StopBistMode();
        }

        private void disableIPFunc()
        {
            string txtbaseClearOriginal;
            string txtMClearOriginal;

            //disable Demura, CM, and IR
            cmdstr = "FF,78,38,0A;90,00;FF,78,38,13;60,00;FF,78,38,00;95,00";

            cmdstr = cmdstr.Replace(";", "\r\n");
            frmHelp.txtProcessDrivercode(cmdstr, out txtbaseClearOriginal, out txtMClearOriginal);
            //MainForm.SendCmd(0);    //Write by Low Speed
            frmHelp.SendCmd(4);    //Write by High Speed

            Delay(500);
        }


        private float readVGP(int vgpAddrH, int vgpAddrL)
        {
            string txtbaseClearOriginal;
            string txtMClearOriginal;

            int nVGPIdx = 0, a, b;
            float fVGP;

            //switch to page 0C
            cmdstr = "FF,78,38,0C";

            cmdstr = cmdstr.Replace(";", "\r\n");
            frmHelp.txtProcessDrivercode(cmdstr, out txtbaseClearOriginal, out txtMClearOriginal);
            //MainForm.SendCmd(0);    //低速写
            frmHelp.SendCmd(4);    //高速写

            // get value of address 'vgpAddrH' -> a
            txt_Reg_Data_WR.Text = vgpAddrH.ToString("X2");
            ILI8818_Others_Click(btn_Reg_W, null);
            Delay(250);
            a = retRegData;

            // get value of address 'vgpAddrL' -> b
            txt_Reg_Data_WR.Text = vgpAddrL.ToString("X2");
            ILI8818_Others_Click(btn_Reg_W, null);
            Delay(250);
            b = retRegData;

            nVGPIdx = (a << 8) + b;

            //switch to page 0
            cmdstr = "FF,78,38,00";

            cmdstr = cmdstr.Replace(";", "\r\n");
            frmHelp.txtProcessDrivercode(cmdstr, out txtbaseClearOriginal, out txtMClearOriginal);
            //MainForm.SendCmd(0);    //低速写
            frmHelp.SendCmd(4);    //高速写

            fVGP = (nVGPIdx - 16) * 0.01f + 0.4f;

            Delay(500);

            return fVGP;
        }

        private void GetCAData(out float x, out float y, out float Lv)
        {
            frmHelp.Msr_CASDK();
            // Msr_CA310();
            Delay(500);

            x = (float)frmHelp.CASDK_x;
            y = (float)frmHelp.CASDK_y;
            Lv = (float)frmHelp.CASDK_LUM;

            //x = (float)auto_x;
            //y = (float)auto_y;
            //Lv = (float)auto_lum;
        }

        private void writeVGP(int vgpAddrH, int vgpAddrL, float value)
        {
            string txtbaseClearOriginal;
            string txtMClearOriginal;

            int Idx;
            float f;

            f = (value - 0.4f) / 0.01f;

            Idx = (int)(f + 0.5f) + 0x10; //ROUND()

            //switch to page 0C
            cmdstr = "FF,78,38,0C";

            // set high byte of Idx into address 'vgpAddrH'
            // set low byte of Idx into address 'vgpAddrH'
            cmdstr = cmdstr + ";" + vgpAddrH.ToString("X2") + "," + ((Idx & 0x0000FF00) >> 8).ToString("X2");
            cmdstr = cmdstr + ";" + vgpAddrL.ToString("X2") + "," + (Idx & 0x000000FF).ToString("X2");

            //switch to page 0
            cmdstr = cmdstr + ";" + "FF,78,38,00";

            cmdstr = cmdstr.Replace(";", "\r\n");
            frmHelp.txtProcessDrivercode(cmdstr, out txtbaseClearOriginal, out txtMClearOriginal);
            //MainForm.SendCmd(0);    //低速写
            frmHelp.SendCmd(4);    //高速写

            Delay(500);
        }

        private void ReadGammaOfLastOnePoint(int nPage, int[] nInitGamma)
        {
            string txtbaseClearOriginal;
            string txtMClearOriginal;

            int a, b;

            //switch to page 'nPage'
            cmdstr = "FF,78,38," + nPage.ToString("X2");

            cmdstr = cmdstr.Replace(";", "\r\n");
            frmHelp.txtProcessDrivercode(cmdstr, out txtbaseClearOriginal, out txtMClearOriginal);
            //MainForm.SendCmd(0);    //低速写
            frmHelp.SendCmd(4);    //高速写

            //read value of address '2E' -> a
            //read value of address '2F' -> b
            txt_Reg_Data_WR.Text = "2E";
            ILI8818_Others_Click(btn_Reg_R, null);
            Delay(250);
            a = retRegData;
            txt_Reg_Data_WR.Text = "2F";
            ILI8818_Others_Click(btn_Reg_R, null);
            Delay(250);
            b = retRegData;
            nInitGamma[0] = ((a & 0x0000000F) << 8) + b;

            //read value of address '5E' -> a
            //read value of address '5F' -> b
            txt_Reg_Data_WR.Text = "5E";
            ILI8818_Others_Click(btn_Reg_R, null);
            Delay(250);
            a = retRegData;
            txt_Reg_Data_WR.Text = "5F";
            ILI8818_Others_Click(btn_Reg_R, null);
            Delay(250);
            b = retRegData;
            nInitGamma[1] = ((a & 0x0000000F) << 8) + b;

            //read value of address '8E' -> a
            //read value of address '8F' -> b
            txt_Reg_Data_WR.Text = "8E";
            ILI8818_Others_Click(btn_Reg_R, null);
            Delay(250);
            a = retRegData;
            txt_Reg_Data_WR.Text = "8F";
            ILI8818_Others_Click(btn_Reg_R, null);
            Delay(250);
            b = retRegData;
            nInitGamma[2] = ((a & 0x0000000F) << 8) + b;

            //swtich page 00
            cmdstr = "FF,78,38,00";

            cmdstr = cmdstr.Replace(";", "\r\n");
            frmHelp.txtProcessDrivercode(cmdstr, out txtbaseClearOriginal, out txtMClearOriginal);
            //MainForm.SendCmd(0);    //低速写
            frmHelp.SendCmd(4);    //高速写

            Delay(500);
        }

        private void WriteGammaOfLastOnePoint(int nPage, int gammaR, int gammaG, int gammaB)
        {
            string txtbaseClearOriginal;
            string txtMClearOriginal;

            //switch to page 'nPage'
            cmdstr = "FF,78,38," + nPage.ToString("X2");

            //write high byte value of gammaR into address '2E'
            //write low byte value of gammaR into address '2F'
            cmdstr = cmdstr + ";" + "2E," + ((gammaR & 0x0000FF00) >> 8).ToString("X2");
            cmdstr = cmdstr + ";" + "2F," + (gammaR & 0x000000FF).ToString("X2");

            //write high byte value of gammaG into address '5E'
            //write low byte value of gammaG into address '5F'
            cmdstr = cmdstr + ";" + "5E," + ((gammaG & 0x0000FF00) >> 8).ToString("X2");
            cmdstr = cmdstr + ";" + "5F," + (gammaG & 0x000000FF).ToString("X2");

            //write high byte value of gammaB into address '8E'
            //write low byte value of gammaB into address '8F'
            cmdstr = cmdstr + ";" + "8E," + ((gammaB & 0x0000FF00) >> 8).ToString("X2");
            cmdstr = cmdstr + ";" + "8F," + (gammaB & 0x000000FF).ToString("X2");

            //swtich page 00 : REGISTER,FF,3,78,38,00
            cmdstr = cmdstr + ";" + "FF,78,38,00";

            cmdstr = cmdstr.Replace(";", "\r\n");
            frmHelp.txtProcessDrivercode(cmdstr, out txtbaseClearOriginal, out txtMClearOriginal);
            //MainForm.SendCmd(0);    //低速写
            frmHelp.SendCmd(4);    //高速写

            Delay(500);
        }

        private void WriteAllGamma(int page, int[] nGammaIndex)
        {
            string txtbaseClearOriginal;
            string txtMClearOriginal;

            int Addr, iCnt, i;

            //WRITEREGISTER,FF,3,78,38,IntToHex(page);
            cmdstr = "FF,78,38," + page.ToString("X2");

            Addr = 0;
            iCnt = 0;
            for (i = 0; i < 24; i++)
            {
                //WRITEREGISTER,IntToHex(Addr),1,IntToHex((nGammaIndex [iCnt] & 0x0000FF00) >> 8, 2);
                cmdstr = cmdstr + ";" + Addr.ToString("X2") + "," + ((nGammaIndex[iCnt] & 0x0000FF00) >> 8).ToString("X2");
                Addr++;

                //WRITEREGISTER,IntToHex(Addr),1,IntToHex((nGammaIndex [iCnt] & 0x000000FF), 2);
                cmdstr = cmdstr + ";" + Addr.ToString("X2") + "," + ((nGammaIndex[iCnt] & 0x000000FF)).ToString("X2");
                Addr++;

                iCnt++;
            }

            Addr = 0x30;
            iCnt = 24;
            for (i = 0; i < 24; i++)
            {
                //WRITEREGISTER,IntToHex(Addr),1,IntToHex((nGammaIndex [iCnt] & 0x0000FF00) >> 8, 2);
                cmdstr = cmdstr + ";" + Addr.ToString("X2") + "," + ((nGammaIndex[iCnt] & 0x0000FF00) >> 8).ToString("X2");
                Addr++;

                //WRITEREGISTER,IntToHex(Addr),1,IntToHex((nGammaIndex [iCnt] & 0x000000FF), 2);
                cmdstr = cmdstr + ";" + Addr.ToString("X2") + "," + ((nGammaIndex[iCnt] & 0x000000FF)).ToString("X2");
                Addr++;

                iCnt++;
            }

            Addr = 0x60;
            iCnt = 48;
            for (i = 0; i < 24; i++)
            {
                //WRITEREGISTER,IntToHex(Addr),1,IntToHex((nGammaIndex [iCnt] & 0x0000FF00) >> 8, 2);
                cmdstr = cmdstr + ";" + Addr.ToString("X2") + "," + ((nGammaIndex[iCnt] & 0x0000FF00) >> 8).ToString("X2");
                Addr++;

                //WRITEREGISTER,IntToHex(Addr),1,IntToHex((nGammaIndex [iCnt] & 0x000000FF), 2);
                cmdstr = cmdstr + ";" + Addr.ToString("X2") + "," + ((nGammaIndex[iCnt] & 0x000000FF)).ToString("X2");
                Addr++;

                iCnt++;
            }

            //WRITEREGISTER,FF,3,78,38,00;
            cmdstr = cmdstr + ";" + "FF,78,38,00";

            cmdstr = cmdstr.Replace(";", "\r\n");
            frmHelp.txtProcessDrivercode(cmdstr, out txtbaseClearOriginal, out txtMClearOriginal);
            //MainForm.SendCmd(0);    //Write by Low Speed
            frmHelp.SendCmd(4);    //Write by High Speed

            Delay(500);
        }

        private void SetFullPara(int G1, int G2, int G3)
        {
            string txtbaseClearOriginal;
            string txtMClearOriginal;

            int[] nGray = new int[3];
            int value;

            nGray[0] = G1 * 4;
            nGray[1] = G2 * 4;
            nGray[2] = G3 * 4;

            /* BIST mode */
            //REGISTER,FF,3,78,38,02;
            cmdstr = "FF,78,38,02";

            /* BIST mode pattern selection */
            //REGISTER,28,1,00;
            //REGISTER,29,1,00;
            //REGISTER,2A,1,20;
            cmdstr = cmdstr + ";" + "28,00;29,00;2A,20";

            /* Gray pattern setting */
            if (nGray[0] == nGray[1] && nGray[0] == nGray[2])
            {
                //REGISTER,2C,1,IntToHex((nGray [0] & 0x0000FF00)>>2,2);
                //REGISTER,2D,1,IntToHex((nGray [0] & 0x000000FF),2);
                //REGISTER,ED,1,00;
                //REGISTER,EE,1,00;
                //REGISTER,EF,1,00;
                cmdstr = cmdstr + ";" + "2C" + "," + ((nGray[0] & 0x0000FF00) >> 2).ToString("X2");
                cmdstr = cmdstr + ";" + "2D" + "," + (nGray[0] & 0x000000FF).ToString("X2");
                cmdstr = cmdstr + ";" + "ED,00";
                cmdstr = cmdstr + ";" + "EE,00";
                cmdstr = cmdstr + ";" + "EF,00";
            }
            else
            {
                //REGISTER,2C,1,IntToHex((nGray[0] & 0x0000FF00)>>2,2);
                //REGISTER,2D,1,IntToHex((nGray[0] & 0x000000FF),2); 
                cmdstr = cmdstr + ";" + "2C" + "," + ((nGray[0] & 0x0000FF00) >> 2).ToString("X2");
                cmdstr = cmdstr + ";" + "2D" + "," + (nGray[0] & 0x000000FF).ToString("X2");

                value = ((nGray[1] & 0x0000FF00) >> 2) + ((nGray[2] & 0x0000FF00) >> 6) + 1;
                //REGISTER,ED,1, IntToHex((value & 0x000000FF),2);
                //REGISTER,EE,1,IntToHex((nGray[1] & 0x000000FF),2);
                //REGISTER,EF,1,IntToHex((nGray[2] & 0x000000FF),2);
                cmdstr = cmdstr + ";" + "ED" + "," + ((value & 0x000000FF)).ToString("X2");
                cmdstr = cmdstr + ";" + "EE" + "," + (nGray[1] & 0x000000FF).ToString("X2");
                cmdstr = cmdstr + ";" + "EF" + "," + (nGray[2] & 0x000000FF).ToString("X2");
            }

            /* switch to page 0 */
            //REGISTER,FF,3,78,38,00;
            cmdstr = cmdstr + ";" + "FF,78,38,00";

            cmdstr = cmdstr.Replace(";", "\r\n");
            frmHelp.txtProcessDrivercode(cmdstr, out txtbaseClearOriginal, out txtMClearOriginal);
            //MainForm.SendCmd(0);    //低速写
            frmHelp.SendCmd(4);    //高速写

            Delay(500);
        }

        private void ReadAllGamma(int nPage, int[] nGammaIndex)
        {
            string txtbaseClearOriginal;
            string txtMClearOriginal;
            string strRead;

            int Addr, iCnt, a, b;

            //WRITEREGISTER,FF,3,78,38,IntToHex(page);
            cmdstr = "FF,78,38," + nPage.ToString("X2");

            cmdstr = cmdstr.Replace(";", "\r\n");
            frmHelp.txtProcessDrivercode(cmdstr, out txtbaseClearOriginal, out txtMClearOriginal);
            //MainForm.SendCmd(0);    //低速写
            frmHelp.SendCmd(4);    //高速写

            Addr = 0;
            iCnt = 0;
            for (int i = 0; i < 24; i++)
            {
                //a = READREGISTER,IntToHex(Addr),1;
                txt_Reg_Data_WR.Text = Addr.ToString("X2");
                ILI8818_Others_Click(btn_Reg_R, null);
                Delay(250);
                strRead = txt_Reg_Data_WR.Text;
                a = Convert.ToInt32(strRead.Substring(strRead.Length - 2), 16);

                Addr++;

                //b = READREGISTER,IntToHex(Addr),1;
                txt_Reg_Data_WR.Text = Addr.ToString("X2");
                ILI8818_Others_Click(btn_Reg_R, null);
                Delay(250);
                strRead = txt_Reg_Data_WR.Text;
                b = Convert.ToInt32(strRead.Substring(strRead.Length - 2), 16);

                Addr++;

                nGammaIndex[iCnt] = (a << 8) + b;
                iCnt++;
            }

            Addr = 0x30;
            iCnt = 24;
            for (int i = 0; i < 24; i++)
            {
                //a = READREGISTER,IntToHex(Addr),1;
                txt_Reg_Data_WR.Text = Addr.ToString("X2");
                ILI8818_Others_Click(btn_Reg_R, null);
                Delay(250);
                strRead = txt_Reg_Data_WR.Text;
                a = Convert.ToInt32(strRead.Substring(strRead.Length - 2), 16);

                Addr++;

                //b = READREGISTER,IntToHex(Addr),1;
                txt_Reg_Data_WR.Text = Addr.ToString("X2");
                ILI8818_Others_Click(btn_Reg_R, null);
                Delay(250);
                strRead = txt_Reg_Data_WR.Text;
                b = Convert.ToInt32(strRead.Substring(strRead.Length - 2), 16);

                Addr++;

                nGammaIndex[iCnt] = (a << 8) + b;
                iCnt++;
            }

            Addr = 0x60;
            iCnt = 48;
            for (int i = 0; i < 24; i++)
            {
                //a = READREGISTER,IntToHex(Addr),1;
                txt_Reg_Data_WR.Text = Addr.ToString("X2");
                ILI8818_Others_Click(btn_Reg_R, null);
                Delay(250);
                strRead = txt_Reg_Data_WR.Text;
                a = Convert.ToInt32(strRead.Substring(strRead.Length - 2), 16);

                Addr++;

                //b = READREGISTER,IntToHex(Addr),1;
                txt_Reg_Data_WR.Text = Addr.ToString("X2");
                ILI8818_Others_Click(btn_Reg_R, null);
                Delay(250);
                strRead = txt_Reg_Data_WR.Text;
                b = Convert.ToInt32(strRead.Substring(strRead.Length - 2), 16);

                Addr++;

                nGammaIndex[iCnt] = (a << 8) + b;
                iCnt++;
            }

            //WRITEREGISTER,FF,3,78,38,00;
            cmdstr = cmdstr + ";" + "FF,78,38,00";

            cmdstr = cmdstr.Replace(";", "\r\n");
            frmHelp.txtProcessDrivercode(cmdstr, out txtbaseClearOriginal, out txtMClearOriginal);
            //MainForm.SendCmd(0);    //低速写
            frmHelp.SendCmd(4);    //高速写

            Delay(500);
        }

        private void setIRDefaultSetting(int nHeight, int nWidth)
        {
            string txtbaseClearOriginal;
            string txtMClearOriginal;

            int Addr;

            // disable IR function
            //REGISTER,FF,3,78,38,00
            //REGISTER,95,00
            cmdstr = "FF,78,38,00;95,00";

            // set IR register
            //REGISTER,FF,3,78,38,0B
            //REGISTER,90,1,24
            //REGISTER,91,1,(Hbyte of nHeight)
            //REGISTER,92,1,(Lbyte of nHeight)
            //REGISTER,93,1,(Hbyte of nWidth)
            //REGISTER,94,1,(Lbyte of nWidth)
            cmdstr = cmdstr + ";" + "FF,78,38,0B;90,24";
            cmdstr = cmdstr + ";" + "91," + ((nHeight & 0x0000FF00) >> 8).ToString("X2");
            cmdstr = cmdstr + ";" + "92," + ((nHeight & 0x000000FF)).ToString("X2");
            cmdstr = cmdstr + ";" + "93," + ((nWidth & 0x0000FF00) >> 8).ToString("X2");
            cmdstr = cmdstr + ";" + "94," + ((nWidth & 0x000000FF)).ToString("X2");

            Addr = 0x95;
            for (int i = 0; i < 3; i++)
            {
                //REGISTER,Addr+i,1,00;
                //REGISTER,Addr+i+4,1,00;
                cmdstr = cmdstr + ";" + (Addr + i).ToString("X2") + ",00";
                cmdstr = cmdstr + ";" + (Addr + i + 4).ToString("X2") + ",00";
            }

            cmdstr = cmdstr.Replace(";", "\r\n");
            frmHelp.txtProcessDrivercode(cmdstr, out txtbaseClearOriginal, out txtMClearOriginal);
            //MainForm.SendCmd(0);    //Write by Low Speed
            frmHelp.SendCmd(4);    //Write by High Speed
        }

        private void enableIR()
        {
            string txtbaseClearOriginal;
            string txtMClearOriginal;

            cmdstr = "FF,78,38,00;95,10";

            cmdstr = cmdstr.Replace(";", "\r\n");
            frmHelp.txtProcessDrivercode(cmdstr, out txtbaseClearOriginal, out txtMClearOriginal);
            //MainForm.SendCmd(0);    //Write by Low Speed
            frmHelp.SendCmd(4);    //Write by High Speed
        }


        private void setIRSetting(DLLStructure.irSetting_t tIrSetting)
        {
            string txtbaseClearOriginal;
            string txtMClearOriginal;

            int Addr, value, i, j;

            // switch to IR page
            //switchPage(0x0B);
            cmdstr = "FF,78,38,0B";

            Addr = 0x95;
            for (i = 0; i < 3; i++)
            {
                value = Convert.ToInt32(tIrSetting.fPara1[i] * 64 + 0.5);
                //REGISTER,Addr+i,1,value;
                cmdstr = cmdstr + ";" + (Addr + i).ToString("X2") + "," + value.ToString("X2");

                value = Convert.ToInt32(tIrSetting.fPara2[i] * 64 + 0.5);
                //REGISTER,Addr+i+4,1,value;
                cmdstr = cmdstr + ";" + (Addr + i + 4).ToString("X2") + "," + value.ToString("X2");
            }

            Addr = 0x9C;
            for (i = 0; i < 3; i++)
            {
                value = Convert.ToInt32(tIrSetting.fRatio[i] * 64 + 0.5);
                //REGISTER,Addr+i,1,value;
                cmdstr = cmdstr + ";" + (Addr + i).ToString("X2") + "," + value.ToString("X2");

                value = Convert.ToInt32(tIrSetting.fHBMRatio[i] * 64 + 0.5);
                //REGISTER,Addr+i+3,1,value;
                cmdstr = cmdstr + ";" + (Addr + i + 3).ToString("X2") + "," + value.ToString("X2");
            }
            for (i = 1; i <= 3; i++)
            {
                Addr = 0xA2 + (i - 1) * 0x12;
                for (j = 1; j <= 9; j++)
                {
                    value = Convert.ToInt32(tIrSetting.fPara3Lut[(i + 1) * 9 - j] * 8 + 0.5);
                    //REGISTER,Addr,1,IntToHex(value & 0x0000FF00) >> 8, 2);
                    cmdstr = cmdstr + ";" + Addr.ToString("X2") + "," + ((value & 0x0000FF00) >> 8).ToString("X2");
                    Addr++;

                    //REGISTER,Addr,1,IntToHex(value & 0x000000FF), 2);
                    cmdstr = cmdstr + ";" + Addr.ToString("X2") + "," + ((value & 0x000000FF)).ToString("X2");
                    Addr++;
                }
            }

            //switch to page 00
            //switchPage(0); 
            cmdstr = cmdstr + ";" + "FF,78,38,00";

            cmdstr = cmdstr.Replace(";", "\r\n");
            frmHelp.txtProcessDrivercode(cmdstr, out txtbaseClearOriginal, out txtMClearOriginal);
            //MainForm.SendCmd(0);    //Write by Low Speed
            frmHelp.SendCmd(4);    //Write by High Speed
        }

        private void switchPage(int nPage)
        {
            string txtbaseClearOriginal;
            string txtMClearOriginal;

            cmdstr = "FF,78,38," + nPage.ToString("X2");

            cmdstr = cmdstr.Replace(";", "\r\n");
            frmHelp.txtProcessDrivercode(cmdstr, out txtbaseClearOriginal, out txtMClearOriginal);
            //MainForm.SendCmd(0);    //Write by Low Speed
            frmHelp.SendCmd(4);    //Write by High Speed
        }

        private void disableIR()
        {
            string txtbaseClearOriginal;
            string txtMClearOriginal;

            cmdstr = "FF,78,38,00;95,00";

            cmdstr = cmdstr.Replace(";", "\r\n");
            frmHelp.txtProcessDrivercode(cmdstr, out txtbaseClearOriginal, out txtMClearOriginal);
            //MainForm.SendCmd(0);    //Write by Low Speed
            frmHelp.SendCmd(4);    //Write by High Speed
        }

        private void switchMode(int mode)
        {
            string txtbaseClearOriginal;
            string txtMClearOriginal;

            cmdstr = "FF,78,38,00;53," + mode.ToString("X2");

            cmdstr = cmdstr.Replace(";", "\r\n");
            frmHelp.txtProcessDrivercode(cmdstr, out txtbaseClearOriginal, out txtMClearOriginal);
            //MainForm.SendCmd(0);    //Write by Low Speed
            frmHelp.SendCmd(4);    //Write by High Speed
        }

        private void WriteSomeGammaIndex(int page, int[] nGammaIndex, int num)
        {
            string txtbaseClearOriginal;
            string txtMClearOriginal;

            int Addr, iCnt, i;

            //WRITEREGISTER,FF,3,78,38,IntToHex(page);
            cmdstr = "FF,78,38," + page.ToString("X2");

            Addr = 0x30 - (num * 2);
            iCnt = 24 - num;
            for (i = 0; i < num; i++)
            {
                //WRITEREGISTER,IntToHex(Addr),1,IntToHex((nGammaIndex [iCnt] & 0x0000FF00) >> 8, 2);
                cmdstr = cmdstr + ";" + Addr.ToString("X2") + "," + ((nGammaIndex[iCnt] & 0x0000FF00) >> 8).ToString("X2");
                Addr++;

                //WRITEREGISTER,IntToHex(Addr),1,IntToHex((nGammaIndex [iCnt] & 0x000000FF), 2);
                cmdstr = cmdstr + ";" + Addr.ToString("X2") + "," + ((nGammaIndex[iCnt] & 0x000000FF)).ToString("X2");
                Addr++;

                iCnt++;
            }

            Addr = 0x60 - (num * 2);
            iCnt = 48 - num;
            for (i = 0; i < num; i++)
            {
                //WRITEREGISTER,IntToHex(Addr),1,IntToHex((nGammaIndex [iCnt] & 0x0000FF00) >> 8, 2);
                cmdstr = cmdstr + ";" + Addr.ToString("X2") + "," + ((nGammaIndex[iCnt] & 0x0000FF00) >> 8).ToString("X2");
                Addr++;

                //WRITEREGISTER,IntToHex(Addr),1,IntToHex((nGammaIndex [iCnt] & 0x000000FF), 2);
                cmdstr = cmdstr + ";" + Addr.ToString("X2") + "," + ((nGammaIndex[iCnt] & 0x000000FF)).ToString("X2");
                Addr++;

                iCnt++;
            }

            Addr = 0x90 - (num * 2);
            iCnt = 72 - num;
            for (i = 0; i < num; i++)
            {
                //WRITEREGISTER,IntToHex(Addr),1,IntToHex((nGammaIndex [iCnt] & 0x0000FF00) >> 8, 2);
                cmdstr = cmdstr + ";" + Addr.ToString("X2") + "," + ((nGammaIndex[iCnt] & 0x0000FF00) >> 8).ToString("X2");
                Addr++;

                //WRITEREGISTER,IntToHex(Addr),1,IntToHex((nGammaIndex [iCnt] & 0x000000FF), 2);
                cmdstr = cmdstr + ";" + Addr.ToString("X2") + "," + ((nGammaIndex[iCnt] & 0x000000FF)).ToString("X2");
                Addr++;

                iCnt++;
            }

            //WRITEREGISTER,FF,3,78,38,00;
            cmdstr = cmdstr + ";" + "FF,78,38,00";

            cmdstr = cmdstr.Replace(";", "\r\n");
            frmHelp.txtProcessDrivercode(cmdstr, out txtbaseClearOriginal, out txtMClearOriginal);
            //MainForm.SendCmd(0);    //Write by Low Speed
            frmHelp.SendCmd(4);    //Write by High Speed

            Delay(500);
        }

        //****************************Gamma调整功能****************************/
        private int[] nNewGammaIndexTable = new int[24 * 3];
        private int[] anHBMGammaIndexTable = new int[24 * 3];
        private int gnNormPoint;
        private int gnHBMNormPoint;
        private int gnLutParam;
        private int[] gnNormGammaIndex = new int[3];
        private int[] gnNorm2GammaIndex = new int[3];
        private int[] gnNorm3GammaIndex = new int[3];
        private int[] gnAODGammaIndex = new int[3];
        private float gfNorm2VGMP, gfNorm2VGSP;

        public DLLStructure.gammaParam_t tGammaParam;
        public DLLStructure.irParam_t tIrParam;
        public DLLStructure.irSetting_t tIrSetting;

        [DllImport(".\\x_ILITEK\\IRC\\IliGammaTune_x86.dll", CallingConvention = CallingConvention.Cdecl, ExactSpelling = false)]
        public static extern void setDbgMode(int mode);
        [DllImport(".\\x_ILITEK\\IRC\\IliGammaTune_x86.dll", CallingConvention = CallingConvention.Cdecl, ExactSpelling = false)]
        public static extern void gammaSetParameter(ref DLLStructure.gammaParam_t tGammaparam);
        [DllImport(".\\x_ILITEK\\IRC\\IliGammaTune_x86.dll", CallingConvention = CallingConvention.Cdecl, ExactSpelling = false)]
        public static extern float genCoeficient();
        [DllImport(".\\x_ILITEK\\IRC\\IliGammaTune_x86.dll", CallingConvention = CallingConvention.Cdecl, ExactSpelling = false)]
        public static extern int calNodeGamma(int nCurrGammaPoint, float[] fMeasuredxyY, float fTolerance, float fTolerance_c, int[] nInitGamma, int[] nSaveInitGamma);
        [DllImport(".\\x_ILITEK\\IRC\\IliGammaTune_x86.dll", CallingConvention = CallingConvention.Cdecl, ExactSpelling = false)]
        public static extern void preCalNodeGamma(int nCurrGammaPoint, int nPreGammaPoint, int[] nInitGamma);
        [DllImport(".\\x_ILITEK\\IRC\\IliGammaTune_x86.dll", CallingConvention = CallingConvention.Cdecl, ExactSpelling = false)]
        public static extern void InterpolateGamma(int[] anGammaIndex, int[] nTuneIndex, int nTunePointNum);

        [DllImport(".\\x_ILITEK\\IRC\\IliGammaTune_x86.dll", CallingConvention = CallingConvention.Cdecl, ExactSpelling = false)]
        public static extern void irSetParameter(ref DLLStructure.irParam_t tIrParam);
        [DllImport(".\\x_ILITEK\\IRC\\IliGammaTune_x86.dll", CallingConvention = CallingConvention.Cdecl, ExactSpelling = false)]
        public static extern void irGetSetting(ref DLLStructure.irSetting_t tIrSetting);

        [DllImport(".\\x_ILITEK\\IRC\\IliGammaTune_x86.dll", CallingConvention = CallingConvention.Cdecl, ExactSpelling = false)]
        public static extern int irSaveSetting();

        [DllImport(".\\x_ILITEK\\IRC\\IliGammaTune_x86.dll", CallingConvention = CallingConvention.Cdecl, ExactSpelling = false)]
        public static extern void irCalSetting(int[] anGammaIndexTable, float[] afCurrentLut, float[] fxyYForTwoBlkRGBW, float[] fxyYForFullRGBW, float[] fxyYForHalfNearFar);

        [DllImport(".\\x_ILITEK\\IRC\\IliGammaTune_x86.dll", CallingConvention = CallingConvention.Cdecl, ExactSpelling = false)]
        public static extern int irUpdatePara(int[] anGammaIndexTable, float fLvFull, float fLvBlock, float fLvFullComp, float fLvBlockComp, float fTolerance);

        [DllImport(".\\x_ILITEK\\IRC\\IliGammaTune_x86.dll", CallingConvention = CallingConvention.Cdecl, ExactSpelling = false)]
        public static extern int irCalRatio(int[] anGammaIndexTable, float[] fxyYForBlockRGB, float[] fTargetxyY, float[] fxyYFullComp, float fTolerance, int nMode);
        [DllImport(".\\x_ILITEK\\IRC\\IliGammaTune_x86.dll", CallingConvention = CallingConvention.Cdecl, ExactSpelling = false)]
        public static extern int irGenHBMGamma(int[] nNorGammaIndexTable, int[] anHBMGammaIndexTable, float fRecordLv, float[] afMeasuredLv, float[] fxyYFull);

        [DllImport(".\\x_ILITEK\\IRC\\IliGammaTune_x86.dll", CallingConvention = CallingConvention.Cdecl, ExactSpelling = false)]
        public static extern int CRmatrix_v3(int[,] code, double[,] RGBWxy_ori, int[,] RGBLV, double[,] xy_tar, int N, int OGPen);

        bool StopTune = false;

        private void btnTuneGammaN2_Click(object sender, EventArgs e)
        {
            string txtbaseClearOriginal;
            string txtMClearOriginal;

            // get value from tool interface
            int nHeight = int.Parse(txtResH.Text);
            int nWidth = int.Parse(txtResW.Text);
            int nNotchHeight = int.Parse(txtNotchH.Text);
            int blkImgSize = int.Parse(txtBlkImgSize.Text);

            float fNormTargetLv = float.Parse(txtNormDefLv.Text);
            float fNormTargetMinLv = float.Parse(txtNormDefMinLv.Text);
            float fNormTargetx = float.Parse(txtNormDefx.Text);
            float fNormTargety = float.Parse(txtNormDefy.Text);
            float fNormTolerance = float.Parse(txtNormTolerance.Text);
            float fTargetGamma = float.Parse(txtDefGamma.Text);

            int nTunePointNum = 24;
            int[] nTuneIndex = new int[24] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23 };

            int nVGMPAddrH, nVGMPAddrL, nVGSPAddrH, nVGSPAddrL;
            int[] nInitGamma = new int[3];
            int[] nSaveInitGamma = new int[3];
            float[] fMeasuredxyY = new float[3];
            float fx, fy, fLv;
            int nCurrGammaPoint, nPreGammaPoint;
            int loopCnt, nTestOK, i;
            int nPage;

            int[] nBlkBoxSize = new int[4];
            int[] nFullBoxSize = new int[4];

            tGammaParam = new DLLStructure.gammaParam_t();

            int nNorm;

            StopTune = false;
            btnTuneGammaN2.Enabled = false;

            //* * * * * * * * * *
            //* step 1 : get Normalize Point from IC or set by manual
            //* * * * * * * * * *
            nNorm = gnNormPoint;

            //* * * * * * * * * *
            //* step 2 : disable Demura, IR, CM function
            //* * * * * * * * * *
            disableIPFunc();

            //* * * * * * * * * *
            //* step 3 : get gamma bonding point from IC or set by manual
            //* * * * * * * * * *
            int nGammaPointNum = 24;
            tGammaParam.nGammaPointNum = nGammaPointNum;
            tGammaParam.anGammaPoint = new int[24] {0, 4, 12, 20, 28, 32, 36, 40, 44, 52, 84, 92, 112, 144, 176,
                                                  212, 340, 360, 616, 748, 812, 828, 956, 1020};

            tGammaParam.nCoefGammaNum = 5;
            tGammaParam.anCoefGamma = new int[5] { 4000, 3200, 2400, 1600, 1100 };

            tGammaParam.fxyYForRGB = new float[9];
            tGammaParam.coefxyY = new float[15];

            //* * * * * * * * * *
            //* step 4 : set coordinate of corner for tuning pattern
            //* * * * * * * * * *
            nBlkBoxSize[0] = (nWidth - blkImgSize) / 2;
            nBlkBoxSize[1] = (nHeight - blkImgSize) / 2;
            nBlkBoxSize[2] = (nWidth + blkImgSize) / 2;
            nBlkBoxSize[3] = (nHeight + blkImgSize) / 2;

            //set debug mode
            setDbgMode(1);

            //= = = = = = = = = = = = = = =
            // tune first normal gamma
            //= = = = = = = = = = = = = = =
            // set page number
            nPage = 0x0A;
            // switch to prepare tuning gamma page
            //swtich to page 00
            //REGISTER,FF,3,78,38,00
            //Write 03,FF (2 byte) into address '51'
            cmdstr = "FF,78,38,00;51,00,2D";

            cmdstr = cmdstr.Replace(";", "\r\n");
            frmHelp.txtProcessDrivercode(cmdstr, out txtbaseClearOriginal, out txtMClearOriginal);
            //MainForm.SendCmd(0);    //Write by Low Speed
            frmHelp.SendCmd(4);    //Write by High Speed

            //* * * * * * * * * *
            //* step 5 : set target value : Lv, x, y, tolerance, gamma
            //* * * * * * * * * *
            tGammaParam.fTargetx = fNormTargetx;
            tGammaParam.fTargety = fNormTargety;
            tGammaParam.fTargetGamma = fTargetGamma;
            tGammaParam.fTolerance = fNormTolerance;
            tGammaParam.fTargetLv = fNormTargetMinLv + (0x2D - 0x01) * ((fNormTargetLv - fNormTargetMinLv) / (0x3FF - 0x01));
            tGammaParam.nScale = nNorm;

            //* * * * * * * * * *
            //* step 6 : get VGMP / VGSP
            //* * * * * * * * * *
            nVGMPAddrH = 0x90 + (nPage - 0x09) * 4;
            nVGMPAddrL = 0x91 + (nPage - 0x09) * 4;
            nVGSPAddrH = 0x92 + (nPage - 0x09) * 4;
            nVGSPAddrL = 0x93 + (nPage - 0x09) * 4;
            if (gfNorm2VGMP < 0.00001 || gfNorm2VGSP < 0.00001)
            {
                tGammaParam.fVGMP = readVGP(nVGMPAddrH, nVGMPAddrL);
                tGammaParam.fVGSP = readVGP(nVGSPAddrH, nVGSPAddrL);
            }
            else
            {
                tGammaParam.fVGMP = gfNorm2VGMP;
                tGammaParam.fVGSP = gfNorm2VGSP;
            }

            //* * * * * * * * * *
            //* step 7 : show bist mode black pattern and measure its luminance
            //* * * * * * * * * *
            SetBlkPara(0, 0, 0, nBlkBoxSize[0], nBlkBoxSize[1], nBlkBoxSize[2], nBlkBoxSize[3]);
            StartBistMode();
            GetCAData(out fx, out fy, out fLv);
            tGammaParam.fBlackLv = fLv;

            //* * * * * * * * * *
            //* step 8 : show bist mode RGB 255 block pattern and measure their x, y, luminance
            //* * * * * * * * * *
            SetBlkPara(255, 0, 0, nBlkBoxSize[0], nBlkBoxSize[1], nBlkBoxSize[2], nBlkBoxSize[3]);
            GetCAData(out tGammaParam.fxyYForRGB[0], out tGammaParam.fxyYForRGB[1], out tGammaParam.fxyYForRGB[2]);

            SetBlkPara(0, 255, 0, nBlkBoxSize[0], nBlkBoxSize[1], nBlkBoxSize[2], nBlkBoxSize[3]);
            GetCAData(out tGammaParam.fxyYForRGB[3], out tGammaParam.fxyYForRGB[4], out tGammaParam.fxyYForRGB[5]);

            SetBlkPara(0, 0, 255, nBlkBoxSize[0], nBlkBoxSize[1], nBlkBoxSize[2], nBlkBoxSize[3]);
            GetCAData(out tGammaParam.fxyYForRGB[6], out tGammaParam.fxyYForRGB[7], out tGammaParam.fxyYForRGB[8]);

            //* * * * * * * * * *
            //* step 9 : show bist mode W 255 block pattern with different gamma index 
            //*          and measure their x, y, luminance
            //* * * * * * * * * *
            // Prestored gamma index of last one bonding point
            if (gnNorm2GammaIndex[0] == 0 || gnNorm2GammaIndex[1] == 0 || gnNorm2GammaIndex[2] == 0)
            {
                ReadGammaOfLastOnePoint(nPage, nInitGamma);
            }
            else
            {
                for (i = 0; i < 3; i++)
                {
                    nInitGamma[i] = gnNorm2GammaIndex[i];
                }
            }

            SetBlkPara(255, 255, 255, nBlkBoxSize[0], nBlkBoxSize[1], nBlkBoxSize[2], nBlkBoxSize[3]);
            for (i = 0; i < 5; i++)
            {
                WriteGammaOfLastOnePoint(nPage, tGammaParam.anCoefGamma[i], tGammaParam.anCoefGamma[i], tGammaParam.anCoefGamma[i]);
                GetCAData(out tGammaParam.coefxyY[i * 3 + 0], out tGammaParam.coefxyY[i * 3 + 1], out tGammaParam.coefxyY[i * 3 + 2]);
            }

            // restore gamma index  of last one bonding point
            WriteGammaOfLastOnePoint(nPage, nInitGamma[0], nInitGamma[1], nInitGamma[2]);

            //* * * * * * * * * *
            //* step 10 : set gamma parameter and calculate coefficient 
            //*           and return suitable VGSP to write into register
            //* * * * * * * * * *
            gammaSetParameter(ref tGammaParam);
            tGammaParam.fVGSP = genCoeficient();

            writeVGP(nVGSPAddrH, nVGSPAddrL, tGammaParam.fVGSP);

            //txtNorm1VGSP.Text = tGammaParam.fVGSP.ToString();

            //* * * * * * * * * *
            //* step 11: tune gamma index for each gamma point from hight gray to low gray
            //* * * * * * * * * *
            // initial gamma index to 0
            for (i = 0; i < 72; i++)
            {
                nNewGammaIndexTable[i] = 0;
            }

            for (i = nTunePointNum - 1; i >= 0; i--)
            {
                frmHelp.textBox1.Text += "Tune Point " + (i + 1).ToString() + "\r\n";
                frmHelp.textBox1.SelectionStart = frmHelp.textBox1.TextLength;
                frmHelp.textBox1.ScrollToCaret();

                if (tGammaParam.anGammaPoint[nTuneIndex[i]] == 0)
                    continue;

                nCurrGammaPoint = tGammaParam.anGammaPoint[nTuneIndex[i]];

                if (i < (nTunePointNum - 1))
                {
                    nPreGammaPoint = tGammaParam.anGammaPoint[nTuneIndex[i + 1]];

                    // 提前計算下一個綁點的合適gamma index
                    preCalNodeGamma(nCurrGammaPoint, nPreGammaPoint, nInitGamma);
                    WriteGammaOfLastOnePoint(nPage, nInitGamma[0], nInitGamma[1], nInitGamma[2]);
                }

                float fTolerance = tGammaParam.fTolerance;
                float fTolerance_c = tGammaParam.fTolerance;
                loopCnt = 0;
                do
                {
                    GetCAData(out fMeasuredxyY[0], out fMeasuredxyY[1], out fMeasuredxyY[2]);

                    //根據輸入的光學資料,計算當前綁點合適的gamma index, 並將其寫入IC register
                    nTestOK = calNodeGamma(nCurrGammaPoint, fMeasuredxyY, fTolerance, fTolerance_c,
                                            nInitGamma, nSaveInitGamma);
                    WriteGammaOfLastOnePoint(nPage, nInitGamma[0], nInitGamma[1], nInitGamma[2]);

                    loopCnt++;

                    if (StopTune)
                    {
                        StopBistMode();
                        frmHelp.GrayShow(0, 0, 0);
                        btnTuneGammaN2.Enabled = true;
                        return;
                    }
                } while (nTestOK == 0 && loopCnt < 9);

                //若Tune了9次還逹不到Tolerance要求,則改用誤差最小的那一組gamma index
                if (nTestOK == 0 && loopCnt >= 9)
                {
                    nInitGamma[0] = nSaveInitGamma[0];
                    nInitGamma[1] = nSaveInitGamma[1];
                    nInitGamma[2] = nSaveInitGamma[2];
                }

                // 暫存每一組Tune好的綁點gamma index
                nNewGammaIndexTable[nTuneIndex[i]] = nInitGamma[0];
                nNewGammaIndexTable[nTuneIndex[i] + nGammaPointNum] = nInitGamma[1];
                nNewGammaIndexTable[nTuneIndex[i] + nGammaPointNum * 2] = nInitGamma[2];
            }

            StopBistMode();
            frmHelp.GrayShow(0, 0, 0);

            //* * * * * * * * * *
            // step 12 : 若未Tune滿24個綁點gamma index, 其餘綁點的gamma index使用內插計算方式
            //* * * * * * * * * *
            InterpolateGamma(nNewGammaIndexTable, nTuneIndex, nTunePointNum);

            //* * * * * * * * * *
            // step 13: 將24個綁點的gamma index寫入相對應的register內
            //* * * * * * * * * *
            WriteAllGamma(nPage, nNewGammaIndexTable);

            //* * * * * * * * * *
            // step 14: 將24個綁點的gamma index輸出到外部檔案
            //* * * * * * * * * *
            int Addr = 0;
            int nVGMPIdx = (int)(((tGammaParam.fVGMP - 0.4) / 0.01) + 0.5f) + 0x10;
            int nVGSPIdx = (int)(((tGammaParam.fVGSP - 0.4) / 0.01) + 0.5f) + 0x10;

            string strData;
            string strVisionox = System.Windows.Forms.Application.StartupPath + "/ILI8818_gamma_page" + nPage.ToString("X2") + "_" + (tGammaParam.fTargetLv).ToString() + "nits_visionox.txt";
            string strILI = System.Windows.Forms.Application.StartupPath + "/ILI8818_gamma_page" + nPage.ToString("X2") + "_" + (tGammaParam.fTargetLv).ToString() + "nits_ili.txt";
            StreamWriter swVisionox = new StreamWriter(strVisionox);
            StreamWriter swILI = new StreamWriter(strILI);

            //Visionox format
            NumericUpDown[] NUMR = new NumericUpDown[] { num_ILI8818_R0, num_ILI8818_R1, num_ILI8818_R2, num_ILI8818_R3, num_ILI8818_R4, num_ILI8818_R5, num_ILI8818_R6, num_ILI8818_R7, num_ILI8818_R8, num_ILI8818_R9, num_ILI8818_R10, num_ILI8818_R11, num_ILI8818_R12, num_ILI8818_R13, num_ILI8818_R14, num_ILI8818_R15, num_ILI8818_R16, num_ILI8818_R17, num_ILI8818_R18, num_ILI8818_R19, num_ILI8818_R20, num_ILI8818_R21, num_ILI8818_R22, num_ILI8818_R23 };
            NumericUpDown[] NUMG = new NumericUpDown[] { num_ILI8818_G0, num_ILI8818_G1, num_ILI8818_G2, num_ILI8818_G3, num_ILI8818_G4, num_ILI8818_G5, num_ILI8818_G6, num_ILI8818_G7, num_ILI8818_G8, num_ILI8818_G9, num_ILI8818_G10, num_ILI8818_G11, num_ILI8818_G12, num_ILI8818_G13, num_ILI8818_G14, num_ILI8818_G15, num_ILI8818_G16, num_ILI8818_G17, num_ILI8818_G18, num_ILI8818_G19, num_ILI8818_G20, num_ILI8818_G21, num_ILI8818_G22, num_ILI8818_G23 };
            NumericUpDown[] NUMB = new NumericUpDown[] { num_ILI8818_B0, num_ILI8818_B1, num_ILI8818_B2, num_ILI8818_B3, num_ILI8818_B4, num_ILI8818_B5, num_ILI8818_B6, num_ILI8818_B7, num_ILI8818_B8, num_ILI8818_B9, num_ILI8818_B10, num_ILI8818_B11, num_ILI8818_B12, num_ILI8818_B13, num_ILI8818_B14, num_ILI8818_B15, num_ILI8818_B16, num_ILI8818_B17, num_ILI8818_B18, num_ILI8818_B19, num_ILI8818_B20, num_ILI8818_B21, num_ILI8818_B22, num_ILI8818_B23 };

            strData = "FF,78,38," + nPage.ToString("X2");
            swVisionox.WriteLine(strData);
            Addr = 0;
            for (i = 0; i < 72; i++)
            {
                strData = Addr.ToString("X2") + "," + ((nNewGammaIndexTable[i] & 0x0000FF00) >> 8).ToString("X2");
                swVisionox.WriteLine(strData);
                Addr++;

                strData = Addr.ToString("X2") + "," + ((nNewGammaIndexTable[i] & 0x000000FF)).ToString("X2");
                swVisionox.WriteLine(strData);
                Addr++;
            }
            for (i = 0; i < 24; i++)
            {
                //    strData = "R" + i.ToString() + "," + nNewGammaIndexTable[i].ToString("X4") + ",G" + i.ToString() + "," + nNewGammaIndexTable[24 + i].ToString("X4") + ",B" + i.ToString() + "," + nNewGammaIndexTable[48 + i].ToString("X4");
                //    swVisionox.WriteLine(strData);

                NUMR[i].Value = nNewGammaIndexTable[i];
                NUMG[i].Value = nNewGammaIndexTable[i + 24];
                NUMB[i].Value = nNewGammaIndexTable[i + 48];
            }
            swVisionox.WriteLine("FF,78,38,0C");
            strData = nVGMPAddrH.ToString("X2") + "," + ((nVGMPIdx & 0x0000FF00) >> 8).ToString("X2");
            swVisionox.WriteLine(strData);
            strData = nVGMPAddrL.ToString("X2") + "," + ((nVGMPIdx & 0x000000FF)).ToString("X2");
            swVisionox.WriteLine(strData);
            strData = nVGSPAddrH.ToString("X2") + "," + ((nVGSPIdx & 0x0000FF00) >> 8).ToString("X2");
            swVisionox.WriteLine(strData);
            strData = nVGSPAddrL.ToString("X2") + "," + ((nVGSPIdx & 0x000000FF)).ToString("X2");
            swVisionox.WriteLine(strData);

            // ILITek format
            strData = "REGISTER,FF,3,78,38," + nPage.ToString("X2");
            swILI.WriteLine(strData);
            Addr = 0;
            for (i = 0; i < 72; i++)
            {
                strData = "REGISTER," + Addr.ToString("X2") + ",1," + ((nNewGammaIndexTable[i] & 0x0000FF00) >> 8).ToString("X2");
                swILI.WriteLine(strData);
                Addr++;

                strData = "REGISTER," + Addr.ToString("X2") + ",1," + ((nNewGammaIndexTable[i] & 0x000000FF)).ToString("X2");
                swILI.WriteLine(strData);
                Addr++;
            }
            swILI.WriteLine("\nREGISTER,FF,03,78,38,0C");

            strData = "REGISTER," + nVGMPAddrH.ToString("X2") + ",01," + ((nVGMPIdx & 0x0000FF00) >> 8).ToString("X2");
            swILI.WriteLine(strData);
            strData = "REGISTER," + nVGMPAddrL.ToString("X2") + ",01," + ((nVGMPIdx & 0x000000FF)).ToString("X2");
            swILI.WriteLine(strData);
            strData = "REGISTER," + nVGSPAddrH.ToString("X2") + ",01," + ((nVGSPIdx & 0x0000FF00) >> 8).ToString("X2");
            swILI.WriteLine(strData);
            strData = "REGISTER," + nVGSPAddrL.ToString("X2") + ",01," + ((nVGSPIdx & 0x000000FF)).ToString("X2");
            swILI.WriteLine(strData);

            swVisionox.Close();
            swILI.Close();

            frmHelp.textBox1.Text += "Tune Done\r\n";
            frmHelp.textBox1.SelectionStart = frmHelp.textBox1.TextLength;
            frmHelp.textBox1.ScrollToCaret();

            btnTuneGammaN2.Enabled = true;
        }

        private void btnTuneGammaN3_Click(object sender, EventArgs e)
        {
            string txtbaseClearOriginal;
            string txtMClearOriginal;

            // get value from tool interface
            int nHeight = int.Parse(txtResH.Text);
            int nWidth = int.Parse(txtResW.Text);
            int nNotchHeight = int.Parse(txtNotchH.Text);
            int blkImgSize = int.Parse(txtBlkImgSize.Text);

            float fNormTargetLv = float.Parse(txtNormDefLv.Text);
            float fNormTargetMinLv = float.Parse(txtNormDefMinLv.Text);
            float fNormTargetx = float.Parse(txtNormDefx.Text);
            float fNormTargety = float.Parse(txtNormDefy.Text);
            float fNormTolerance = float.Parse(txtNormTolerance.Text);
            float fTargetGamma = float.Parse(txtDefGamma.Text);

            int nTunePointNum = 24;
            int[] nTuneIndex = new int[24] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23 };

            int nVGMPAddrH, nVGMPAddrL, nVGSPAddrH, nVGSPAddrL;
            int[] nInitGamma = new int[3];
            int[] nSaveInitGamma = new int[3];
            float[] fMeasuredxyY = new float[3];
            float fx, fy, fLv;
            int nCurrGammaPoint, nPreGammaPoint;
            int loopCnt, nTestOK, i;
            int nPage;

            int[] nBlkBoxSize = new int[4];
            int[] nFullBoxSize = new int[4];

            tGammaParam = new DLLStructure.gammaParam_t();

            int nNorm;

            StopTune = false;
            btnTuneGammaN3.Enabled = false;

            //* * * * * * * * * *
            //* step 1 : get Normalize Point from IC or set by manual
            //* * * * * * * * * *
            nNorm = gnNormPoint;

            //* * * * * * * * * *
            //* step 2 : disable Demura, IR, CM function
            //* * * * * * * * * *
            disableIPFunc();

            //* * * * * * * * * *
            //* step 3 : get gamma bonding point from IC or set by manual
            //* * * * * * * * * *
            int nGammaPointNum = 24;
            tGammaParam.nGammaPointNum = nGammaPointNum;
            tGammaParam.anGammaPoint = new int[24] {0, 4, 12, 20, 28, 32, 36, 40, 44, 52, 84, 92, 112, 144, 176,
                                                  212, 340, 360, 616, 748, 812, 828, 956, 1020};

            tGammaParam.nCoefGammaNum = 5;
            tGammaParam.anCoefGamma = new int[5] { 4000, 3200, 2400, 1600, 1100 };

            tGammaParam.fxyYForRGB = new float[9];
            tGammaParam.coefxyY = new float[15];

            //* * * * * * * * * *
            //* step 4 : set coordinate of corner for tuning pattern
            //* * * * * * * * * *
            nBlkBoxSize[0] = (nWidth - blkImgSize) / 2;
            nBlkBoxSize[1] = (nHeight - blkImgSize) / 2;
            nBlkBoxSize[2] = (nWidth + blkImgSize) / 2;
            nBlkBoxSize[3] = (nHeight + blkImgSize) / 2;

            //set debug mode
            setDbgMode(1);

            //= = = = = = = = = = = = = = =
            // tune first normal gamma
            //= = = = = = = = = = = = = = =
            // set page number
            nPage = 0x0B;
            // switch to prepare tuning gamma page
            //swtich to page 00
            //REGISTER,FF,3,78,38,00
            //Write 03,FF (2 byte) into address '51'
            cmdstr = "FF,78,38,00;51,00,01";

            cmdstr = cmdstr.Replace(";", "\r\n");
            frmHelp.txtProcessDrivercode(cmdstr, out txtbaseClearOriginal, out txtMClearOriginal);
            //MainForm.SendCmd(0);    //Write by Low Speed
            frmHelp.SendCmd(4);    //Write by High Speed

            //* * * * * * * * * *
            //* step 5 : set target value : Lv, x, y, tolerance, gamma
            //* * * * * * * * * *
            tGammaParam.fTargetx = fNormTargetx;
            tGammaParam.fTargety = fNormTargety;
            tGammaParam.fTargetGamma = fTargetGamma;
            tGammaParam.fTolerance = fNormTolerance;
            tGammaParam.fTargetLv = fNormTargetMinLv;
            tGammaParam.nScale = nNorm;

            //* * * * * * * * * *
            //* step 6 : get VGMP / VGSP
            //* * * * * * * * * *
            nVGMPAddrH = 0x90 + (nPage - 0x09) * 4;
            nVGMPAddrL = 0x91 + (nPage - 0x09) * 4;
            nVGSPAddrH = 0x92 + (nPage - 0x09) * 4;
            nVGSPAddrL = 0x93 + (nPage - 0x09) * 4;
            if (txtNorm3VGMP.Text == "0" || txtNorm3VGSP.Text == "0")
            {
                tGammaParam.fVGMP = readVGP(nVGMPAddrH, nVGMPAddrL);
                tGammaParam.fVGSP = readVGP(nVGSPAddrH, nVGSPAddrL);
            }
            else
            {
                tGammaParam.fVGMP = float.Parse(txtNorm3VGMP.Text);
                tGammaParam.fVGSP = float.Parse(txtNorm3VGSP.Text);
            }

            //* * * * * * * * * *
            //* step 7 : show bist mode black pattern and measure its luminance
            //* * * * * * * * * *
            SetBlkPara(0, 0, 0, nBlkBoxSize[0], nBlkBoxSize[1], nBlkBoxSize[2], nBlkBoxSize[3]);
            StartBistMode();
            GetCAData(out fx, out fy, out fLv);
            tGammaParam.fBlackLv = fLv;

            //* * * * * * * * * *
            //* step 8 : show bist mode RGB 255 block pattern and measure their x, y, luminance
            //* * * * * * * * * *
            SetBlkPara(255, 0, 0, nBlkBoxSize[0], nBlkBoxSize[1], nBlkBoxSize[2], nBlkBoxSize[3]);
            GetCAData(out tGammaParam.fxyYForRGB[0], out tGammaParam.fxyYForRGB[1], out tGammaParam.fxyYForRGB[2]);

            SetBlkPara(0, 255, 0, nBlkBoxSize[0], nBlkBoxSize[1], nBlkBoxSize[2], nBlkBoxSize[3]);
            GetCAData(out tGammaParam.fxyYForRGB[3], out tGammaParam.fxyYForRGB[4], out tGammaParam.fxyYForRGB[5]);

            SetBlkPara(0, 0, 255, nBlkBoxSize[0], nBlkBoxSize[1], nBlkBoxSize[2], nBlkBoxSize[3]);
            GetCAData(out tGammaParam.fxyYForRGB[6], out tGammaParam.fxyYForRGB[7], out tGammaParam.fxyYForRGB[8]);

            //* * * * * * * * * *
            //* step 9 : show bist mode W 255 block pattern with different gamma index 
            //*          and measure their x, y, luminance
            //* * * * * * * * * *
            // Prestored gamma index of last one bonding point
            if (gnNorm3GammaIndex[0] == 0 || gnNorm3GammaIndex[1] == 0 || gnNorm3GammaIndex[2] == 0)
            {
                ReadGammaOfLastOnePoint(nPage, nInitGamma);
            }
            else
            {
                for (i = 0; i < 3; i++)
                {
                    nInitGamma[i] = gnNorm3GammaIndex[i];
                }
            }

            SetBlkPara(255, 255, 255, nBlkBoxSize[0], nBlkBoxSize[1], nBlkBoxSize[2], nBlkBoxSize[3]);
            for (i = 0; i < 5; i++)
            {
                WriteGammaOfLastOnePoint(nPage, tGammaParam.anCoefGamma[i], tGammaParam.anCoefGamma[i], tGammaParam.anCoefGamma[i]);
                GetCAData(out tGammaParam.coefxyY[i * 3 + 0], out tGammaParam.coefxyY[i * 3 + 1], out tGammaParam.coefxyY[i * 3 + 2]);
            }

            // restore gamma index  of last one bonding point
            WriteGammaOfLastOnePoint(nPage, nInitGamma[0], nInitGamma[1], nInitGamma[2]);

            //* * * * * * * * * *
            //* step 10 : set gamma parameter and calculate coefficient 
            //*           and return suitable VGSP to write into register
            //* * * * * * * * * *
            gammaSetParameter(ref tGammaParam);
            tGammaParam.fVGSP = genCoeficient();

            writeVGP(nVGSPAddrH, nVGSPAddrL, tGammaParam.fVGSP);

            txtNorm3VGSP.Text = tGammaParam.fVGSP.ToString();

            //* * * * * * * * * *
            //* step 11: tune gamma index for each gamma point from hight gray to low gray
            //* * * * * * * * * *
            // initial gamma index to 0
            for (i = 0; i < 72; i++)
            {
                nNewGammaIndexTable[i] = 0;
            }

            for (i = nTunePointNum - 1; i >= 0; i--)
            {
                frmHelp.textBox1.Text += "Tune Point " + (i + 1).ToString() + "\r\n";
                frmHelp.textBox1.SelectionStart = frmHelp.textBox1.TextLength;
                frmHelp.textBox1.ScrollToCaret();

                if (tGammaParam.anGammaPoint[nTuneIndex[i]] == 0)
                    continue;

                nCurrGammaPoint = tGammaParam.anGammaPoint[nTuneIndex[i]];

                if (i < (nTunePointNum - 1))
                {
                    nPreGammaPoint = tGammaParam.anGammaPoint[nTuneIndex[i + 1]];

                    // 提前計算下一個綁點的合適gamma index
                    preCalNodeGamma(nCurrGammaPoint, nPreGammaPoint, nInitGamma);
                    WriteGammaOfLastOnePoint(nPage, nInitGamma[0], nInitGamma[1], nInitGamma[2]);
                }

                float fTolerance = tGammaParam.fTolerance;
                float fTolerance_c = tGammaParam.fTolerance;
                loopCnt = 0;
                do
                {
                    GetCAData(out fMeasuredxyY[0], out fMeasuredxyY[1], out fMeasuredxyY[2]);

                    //根據輸入的光學資料,計算當前綁點合適的gamma index, 並將其寫入IC register
                    nTestOK = calNodeGamma(nCurrGammaPoint, fMeasuredxyY, fTolerance, fTolerance_c,
                                            nInitGamma, nSaveInitGamma);
                    WriteGammaOfLastOnePoint(nPage, nInitGamma[0], nInitGamma[1], nInitGamma[2]);

                    loopCnt++;

                    if (StopTune)
                    {
                        StopBistMode();
                        frmHelp.GrayShow(0, 0, 0);
                        btnTuneGammaN3.Enabled = true;
                        return;
                    }
                } while (nTestOK == 0 && loopCnt < 9);

                //若Tune了9次還逹不到Tolerance要求,則改用誤差最小的那一組gamma index
                if (nTestOK == 0 && loopCnt >= 9)
                {
                    nInitGamma[0] = nSaveInitGamma[0];
                    nInitGamma[1] = nSaveInitGamma[1];
                    nInitGamma[2] = nSaveInitGamma[2];
                }

                // 暫存每一組Tune好的綁點gamma index
                nNewGammaIndexTable[nTuneIndex[i]] = nInitGamma[0];
                nNewGammaIndexTable[nTuneIndex[i] + nGammaPointNum] = nInitGamma[1];
                nNewGammaIndexTable[nTuneIndex[i] + nGammaPointNum * 2] = nInitGamma[2];
            }

            StopBistMode();
            frmHelp.GrayShow(0, 0, 0);

            //* * * * * * * * * *
            // step 12 : 若未Tune滿24個綁點gamma index, 其餘綁點的gamma index使用內插計算方式
            //* * * * * * * * * *
            InterpolateGamma(nNewGammaIndexTable, nTuneIndex, nTunePointNum);

            //* * * * * * * * * *
            // step 13: 將24個綁點的gamma index寫入相對應的register內
            //* * * * * * * * * *
            WriteAllGamma(nPage, nNewGammaIndexTable);

            //* * * * * * * * * *
            // step 14: 將24個綁點的gamma index輸出到外部檔案
            //* * * * * * * * * *
            int Addr = 0;
            int nVGMPIdx = (int)(((tGammaParam.fVGMP - 0.4) / 0.01) + 0.5f) + 0x10;
            int nVGSPIdx = (int)(((tGammaParam.fVGSP - 0.4) / 0.01) + 0.5f) + 0x10;

            string strData;
            string strVisionox = System.Windows.Forms.Application.StartupPath + "/ILI8818_gamma_page" + nPage.ToString("X2") + "_" + (tGammaParam.fTargetLv).ToString() + "nits_visionox.txt";
            string strILI = System.Windows.Forms.Application.StartupPath + "/ILI8818_gamma_page" + nPage.ToString("X2") + "_" + (tGammaParam.fTargetLv).ToString() + "nits_ili.txt";
            StreamWriter swVisionox = new StreamWriter(strVisionox);
            StreamWriter swILI = new StreamWriter(strILI);

            //Visionox format
            NumericUpDown[] NUMR = new NumericUpDown[] { num_ILI8818_R0, num_ILI8818_R1, num_ILI8818_R2, num_ILI8818_R3, num_ILI8818_R4, num_ILI8818_R5, num_ILI8818_R6, num_ILI8818_R7, num_ILI8818_R8, num_ILI8818_R9, num_ILI8818_R10, num_ILI8818_R11, num_ILI8818_R12, num_ILI8818_R13, num_ILI8818_R14, num_ILI8818_R15, num_ILI8818_R16, num_ILI8818_R17, num_ILI8818_R18, num_ILI8818_R19, num_ILI8818_R20, num_ILI8818_R21, num_ILI8818_R22, num_ILI8818_R23 };
            NumericUpDown[] NUMG = new NumericUpDown[] { num_ILI8818_G0, num_ILI8818_G1, num_ILI8818_G2, num_ILI8818_G3, num_ILI8818_G4, num_ILI8818_G5, num_ILI8818_G6, num_ILI8818_G7, num_ILI8818_G8, num_ILI8818_G9, num_ILI8818_G10, num_ILI8818_G11, num_ILI8818_G12, num_ILI8818_G13, num_ILI8818_G14, num_ILI8818_G15, num_ILI8818_G16, num_ILI8818_G17, num_ILI8818_G18, num_ILI8818_G19, num_ILI8818_G20, num_ILI8818_G21, num_ILI8818_G22, num_ILI8818_G23 };
            NumericUpDown[] NUMB = new NumericUpDown[] { num_ILI8818_B0, num_ILI8818_B1, num_ILI8818_B2, num_ILI8818_B3, num_ILI8818_B4, num_ILI8818_B5, num_ILI8818_B6, num_ILI8818_B7, num_ILI8818_B8, num_ILI8818_B9, num_ILI8818_B10, num_ILI8818_B11, num_ILI8818_B12, num_ILI8818_B13, num_ILI8818_B14, num_ILI8818_B15, num_ILI8818_B16, num_ILI8818_B17, num_ILI8818_B18, num_ILI8818_B19, num_ILI8818_B20, num_ILI8818_B21, num_ILI8818_B22, num_ILI8818_B23 };

            strData = "FF,78,38," + nPage.ToString("X2");
            swVisionox.WriteLine(strData);
            Addr = 0;
            for (i = 0; i < 72; i++)
            {
                strData = Addr.ToString("X2") + "," + ((nNewGammaIndexTable[i] & 0x0000FF00) >> 8).ToString("X2");
                swVisionox.WriteLine(strData);
                Addr++;

                strData = Addr.ToString("X2") + "," + ((nNewGammaIndexTable[i] & 0x000000FF)).ToString("X2");
                swVisionox.WriteLine(strData);
                Addr++;
            }
            for (i = 0; i < 24; i++)
            {
                //    strData = "R" + i.ToString() + "," + nNewGammaIndexTable[i].ToString("X4") + ",G" + i.ToString() + "," + nNewGammaIndexTable[24 + i].ToString("X4") + ",B" + i.ToString() + "," + nNewGammaIndexTable[48 + i].ToString("X4");
                //    swVisionox.WriteLine(strData);

                NUMR[i].Value = nNewGammaIndexTable[i];
                NUMG[i].Value = nNewGammaIndexTable[i + 24];
                NUMB[i].Value = nNewGammaIndexTable[i + 48];
            }
            swVisionox.WriteLine("FF,78,38,0C");
            strData = nVGMPAddrH.ToString("X2") + "," + ((nVGMPIdx & 0x0000FF00) >> 8).ToString("X2");
            swVisionox.WriteLine(strData);
            strData = nVGMPAddrL.ToString("X2") + "," + ((nVGMPIdx & 0x000000FF)).ToString("X2");
            swVisionox.WriteLine(strData);
            strData = nVGSPAddrH.ToString("X2") + "," + ((nVGSPIdx & 0x0000FF00) >> 8).ToString("X2");
            swVisionox.WriteLine(strData);
            strData = nVGSPAddrL.ToString("X2") + "," + ((nVGSPIdx & 0x000000FF)).ToString("X2");
            swVisionox.WriteLine(strData);

            // ILITek format
            strData = "REGISTER,FF,3,78,38," + nPage.ToString("X2");
            swILI.WriteLine(strData);
            Addr = 0;
            for (i = 0; i < 72; i++)
            {
                strData = "REGISTER," + Addr.ToString("X2") + ",1," + ((nNewGammaIndexTable[i] & 0x0000FF00) >> 8).ToString("X2");
                swILI.WriteLine(strData);
                Addr++;

                strData = "REGISTER," + Addr.ToString("X2") + ",1," + ((nNewGammaIndexTable[i] & 0x000000FF)).ToString("X2");
                swILI.WriteLine(strData);
                Addr++;
            }
            swILI.WriteLine("\nREGISTER,FF,03,78,38,0C");

            strData = "REGISTER," + nVGMPAddrH.ToString("X2") + ",01," + ((nVGMPIdx & 0x0000FF00) >> 8).ToString("X2");
            swILI.WriteLine(strData);
            strData = "REGISTER," + nVGMPAddrL.ToString("X2") + ",01," + ((nVGMPIdx & 0x000000FF)).ToString("X2");
            swILI.WriteLine(strData);
            strData = "REGISTER," + nVGSPAddrH.ToString("X2") + ",01," + ((nVGSPIdx & 0x0000FF00) >> 8).ToString("X2");
            swILI.WriteLine(strData);
            strData = "REGISTER," + nVGSPAddrL.ToString("X2") + ",01," + ((nVGSPIdx & 0x000000FF)).ToString("X2");
            swILI.WriteLine(strData);

            swVisionox.Close();
            swILI.Close();

            frmHelp.textBox1.Text += "Tune Done\r\n";
            frmHelp.textBox1.SelectionStart = frmHelp.textBox1.TextLength;
            frmHelp.textBox1.ScrollToCaret();

            btnTuneGammaN3.Enabled = true;

        }

        private void btnTuneGammaAOD_Click(object sender, EventArgs e)
        {
            string txtbaseClearOriginal;
            string txtMClearOriginal;

            // get value from tool interface
            int nHeight = int.Parse(txtResH.Text);
            int nWidth = int.Parse(txtResW.Text);
            int nNotchHeight = int.Parse(txtNotchH.Text);
            int blkImgSize = int.Parse(txtBlkImgSize.Text);

            blkImgSize = (int)(Math.Sqrt(nHeight * nWidth * 0.15));
            blkImgSize = blkImgSize - (blkImgSize % 2);

            float fAODTargetLv = float.Parse(txtAODDefLv.Text);
            float fAODTargetMinLv = float.Parse(txtNormDefMinLv.Text);
            float fAODTargetx = float.Parse(txtAODDefx.Text);
            float fAODTargety = float.Parse(txtAODDefy.Text);
            float fAODTolerance = float.Parse(txtAODTolerance.Text);
            float fTargetGamma = float.Parse(txtDefGamma.Text);

            int nTunePointNum = 24;
            int[] nTuneIndex = new int[24] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23 };

            int nVGMPAddrH, nVGMPAddrL, nVGSPAddrH, nVGSPAddrL;
            int[] nInitGamma = new int[3];
            int[] nSaveInitGamma = new int[3];
            float[] fMeasuredxyY = new float[3];
            float fx, fy, fLv;
            int nCurrGammaPoint, nPreGammaPoint;
            int loopCnt, nTestOK, i;
            int nPage;

            int[] nBlkBoxSize = new int[4];
            int[] nFullBoxSize = new int[4];

            tGammaParam = new DLLStructure.gammaParam_t();

            int nNorm;

            StopTune = false;
            btnTuneGammaAOD.Enabled = false;

            //* * * * * * * * * *
            //* step 1 : get Normalize Point from IC or set by manual
            //* * * * * * * * * *
            nNorm = gnNormPoint;

            //* * * * * * * * * *
            //* step 2 : disable Demura, IR, CM function
            //* * * * * * * * * *
            disableIPFunc();

            //* * * * * * * * * *
            //* step 3 : get gamma bonding point from IC or set by manual
            //* * * * * * * * * *
            int nGammaPointNum = 24;
            tGammaParam.nGammaPointNum = nGammaPointNum;
            tGammaParam.anGammaPoint = new int[24] {0, 4, 12, 20, 28, 32, 36, 40, 44, 52, 84, 92, 112, 144, 176,
                                                  212, 340, 360, 616, 748, 812, 828, 956, 1020};

            tGammaParam.nCoefGammaNum = 5;
            tGammaParam.anCoefGamma = new int[5] { 4000, 3200, 2400, 1600, 1100 };

            tGammaParam.fxyYForRGB = new float[9];
            tGammaParam.coefxyY = new float[15];

            //* * * * * * * * * *
            //* step 4 : set coordinate of corner for tuning pattern
            //* * * * * * * * * *
            nBlkBoxSize[0] = (nWidth - blkImgSize) / 2;
            nBlkBoxSize[1] = (nHeight - blkImgSize) / 2;
            nBlkBoxSize[2] = (nWidth + blkImgSize) / 2;
            nBlkBoxSize[3] = (nHeight + blkImgSize) / 2;

            //set debug mode
            setDbgMode(1);

            //= = = = = = = = = = = = = = =
            // tune first normal gamma
            //= = = = = = = = = = = = = = =
            // set page number
            nPage = 0x0E;
            // enter AOD mode
            //REGISTER,FF,3,78,38,00
            //REGISTER,53,1,26
            cmdstr = "FF,78,38,00;53,26";

            cmdstr = cmdstr.Replace(";", "\r\n");
            frmHelp.txtProcessDrivercode(cmdstr, out txtbaseClearOriginal, out txtMClearOriginal);
            //MainForm.SendCmd(0);    //Write by Low Speed
            frmHelp.SendCmd(4);    //Write by High Speed

            Delay(1250);

            //* * * * * * * * * *
            //* step 5 : set target value : Lv, x, y, tolerance, gamma
            //* * * * * * * * * *
            tGammaParam.fTargetx = fAODTargetx;
            tGammaParam.fTargety = fAODTargety;
            tGammaParam.fTargetGamma = fTargetGamma;
            tGammaParam.fTolerance = fAODTolerance;
            tGammaParam.fTargetLv = fAODTargetLv;
            tGammaParam.nScale = 255;

            //* * * * * * * * * *
            //* step 6 : get VGMP / VGSP
            //* * * * * * * * * *
            nVGMPAddrH = 0x90 + (nPage - 0x09) * 4;
            nVGMPAddrL = 0x91 + (nPage - 0x09) * 4;
            nVGSPAddrH = 0x92 + (nPage - 0x09) * 4;
            nVGSPAddrL = 0x93 + (nPage - 0x09) * 4;
            if (txtAODVGMP.Text == "0" || txtAODVGSP.Text == "0")
            {
                tGammaParam.fVGMP = readVGP(nVGMPAddrH, nVGMPAddrL);
                tGammaParam.fVGSP = readVGP(nVGSPAddrH, nVGSPAddrL);
            }
            else
            {
                tGammaParam.fVGMP = float.Parse(txtAODVGMP.Text);
                tGammaParam.fVGSP = float.Parse(txtAODVGSP.Text);
            }

            //* * * * * * * * * *
            //* step 7 : show bist mode black pattern and measure its luminance
            //* * * * * * * * * *
            SetBlkPara(0, 0, 0, nBlkBoxSize[0], nBlkBoxSize[1], nBlkBoxSize[2], nBlkBoxSize[3]);
            StartBistMode();
            GetCAData(out fx, out fy, out fLv);
            tGammaParam.fBlackLv = fLv;

            //* * * * * * * * * *
            //* step 8 : show bist mode RGB 255 block pattern and measure their x, y, luminance
            //* * * * * * * * * *
            SetBlkPara(255, 0, 0, nBlkBoxSize[0], nBlkBoxSize[1], nBlkBoxSize[2], nBlkBoxSize[3]);
            GetCAData(out tGammaParam.fxyYForRGB[0], out tGammaParam.fxyYForRGB[1], out tGammaParam.fxyYForRGB[2]);

            SetBlkPara(0, 255, 0, nBlkBoxSize[0], nBlkBoxSize[1], nBlkBoxSize[2], nBlkBoxSize[3]);
            GetCAData(out tGammaParam.fxyYForRGB[3], out tGammaParam.fxyYForRGB[4], out tGammaParam.fxyYForRGB[5]);

            SetBlkPara(0, 0, 255, nBlkBoxSize[0], nBlkBoxSize[1], nBlkBoxSize[2], nBlkBoxSize[3]);
            GetCAData(out tGammaParam.fxyYForRGB[6], out tGammaParam.fxyYForRGB[7], out tGammaParam.fxyYForRGB[8]);

            //* * * * * * * * * *
            //* step 9 : show bist mode W 255 block pattern with different gamma index 
            //*          and measure their x, y, luminance
            //* * * * * * * * * *
            // Prestored gamma index of last one bonding point
            if (gnAODGammaIndex[0] == 0)
            {
                ReadGammaOfLastOnePoint(nPage, nInitGamma);
            }
            else
            {
                for (i = 0; i < 3; i++)
                {
                    nInitGamma[i] = gnAODGammaIndex[i];
                }
            }

            SetBlkPara(255, 255, 255, nBlkBoxSize[0], nBlkBoxSize[1], nBlkBoxSize[2], nBlkBoxSize[3]);
            for (i = 0; i < 5; i++)
            {
                WriteGammaOfLastOnePoint(nPage, tGammaParam.anCoefGamma[i], tGammaParam.anCoefGamma[i], tGammaParam.anCoefGamma[i]);
                GetCAData(out tGammaParam.coefxyY[i * 3 + 0], out tGammaParam.coefxyY[i * 3 + 1], out tGammaParam.coefxyY[i * 3 + 2]);
            }

            // restore gamma index  of last one bonding point
            WriteGammaOfLastOnePoint(nPage, nInitGamma[0], nInitGamma[1], nInitGamma[2]);

            //* * * * * * * * * *
            //* step 10 : set gamma parameter and calculate coefficient 
            //*           and return suitable VGSP to write into register
            //* * * * * * * * * *
            gammaSetParameter(ref tGammaParam);
            tGammaParam.fVGSP = genCoeficient();

            writeVGP(nVGSPAddrH, nVGSPAddrL, tGammaParam.fVGSP);

            //* * * * * * * * * *
            //* step 11: tune gamma index for each gamma point from hight gray to low gray
            //* * * * * * * * * *
            // initial gamma index to 0
            for (i = 0; i < 72; i++)
            {
                nNewGammaIndexTable[i] = 0;
            }

            for (i = nTunePointNum - 1; i >= 0; i--)
            {
                frmHelp.textBox1.Text += "Tune Point " + (i + 1).ToString() + "\r\n";
                frmHelp.textBox1.SelectionStart = frmHelp.textBox1.TextLength;
                frmHelp.textBox1.ScrollToCaret();

                if (tGammaParam.anGammaPoint[nTuneIndex[i]] == 0)
                    continue;

                nCurrGammaPoint = tGammaParam.anGammaPoint[nTuneIndex[i]];

                if (i < (nTunePointNum - 1))
                {
                    nPreGammaPoint = tGammaParam.anGammaPoint[nTuneIndex[i + 1]];

                    // 提前計算下一個綁點的合適gamma index
                    preCalNodeGamma(nCurrGammaPoint, nPreGammaPoint, nInitGamma);
                    WriteGammaOfLastOnePoint(nPage, nInitGamma[0], nInitGamma[1], nInitGamma[2]);
                }

                float fTolerance = tGammaParam.fTolerance;
                float fTolerance_c = tGammaParam.fTolerance;
                loopCnt = 0;
                do
                {
                    GetCAData(out fMeasuredxyY[0], out fMeasuredxyY[1], out fMeasuredxyY[2]);

                    //根據輸入的光學資料,計算當前綁點合適的gamma index, 並將其寫入IC register
                    nTestOK = calNodeGamma(nCurrGammaPoint, fMeasuredxyY, fTolerance, fTolerance_c,
                                            nInitGamma, nSaveInitGamma);
                    WriteGammaOfLastOnePoint(nPage, nInitGamma[0], nInitGamma[1], nInitGamma[2]);

                    loopCnt++;

                    if (StopTune)
                    {
                        StopBistMode();
                        frmHelp.GrayShow(0, 0, 0);

                        // Exit AOD mode
                        //REGISTER,FF,3,78,38,00
                        //REGISTER,53,1,24
                        cmdstr = "FF,78,38,00;53,24";

                        cmdstr = cmdstr.Replace(";", "\r\n");
                        frmHelp.txtProcessDrivercode(cmdstr, out txtbaseClearOriginal, out txtMClearOriginal);
                        //MainForm.SendCmd(0);    //Write by Low Speed
                        frmHelp.SendCmd(4);    //Write by High Speed

                        btnTuneGammaAOD.Enabled = true;
                        return;
                    }
                } while (nTestOK == 0 && loopCnt < 9);

                //若Tune了9次還逹不到Tolerance要求,則改用誤差最小的那一組gamma index
                if (nTestOK == 0 && loopCnt >= 9)
                {
                    nInitGamma[0] = nSaveInitGamma[0];
                    nInitGamma[1] = nSaveInitGamma[1];
                    nInitGamma[2] = nSaveInitGamma[2];
                }

                // 暫存每一組Tune好的綁點gamma index
                nNewGammaIndexTable[nTuneIndex[i]] = nInitGamma[0];
                nNewGammaIndexTable[nTuneIndex[i] + nGammaPointNum] = nInitGamma[1];
                nNewGammaIndexTable[nTuneIndex[i] + nGammaPointNum * 2] = nInitGamma[2];
            }

            StopBistMode();
            frmHelp.GrayShow(0, 0, 0);

            // Exit AOD mode
            //REGISTER,FF,3,78,38,00
            //REGISTER,53,1,24
            cmdstr = "FF,78,38,00;53,24";

            cmdstr = cmdstr.Replace(";", "\r\n");
            frmHelp.txtProcessDrivercode(cmdstr, out txtbaseClearOriginal, out txtMClearOriginal);
            //MainForm.SendCmd(0);    //Write by Low Speed
            frmHelp.SendCmd(4);    //Write by High Speed

            //* * * * * * * * * *
            // step 12 : 若未Tune滿24個綁點gamma index, 其餘綁點的gamma index使用內插計算方式
            //* * * * * * * * * *
            InterpolateGamma(nNewGammaIndexTable, nTuneIndex, nTunePointNum);

            //* * * * * * * * * *
            // step 13: 將24個綁點的gamma index寫入相對應的register內
            //* * * * * * * * * *
            WriteAllGamma(nPage, nNewGammaIndexTable);

            //* * * * * * * * * *
            // step 14: 將24個綁點的gamma index輸出到外部檔案
            //* * * * * * * * * *
            int Addr = 0;
            int nVGMPIdx = (int)(((tGammaParam.fVGMP - 0.4) / 0.01) + 0.5f) + 0x10;
            int nVGSPIdx = (int)(((tGammaParam.fVGSP - 0.4) / 0.01) + 0.5f) + 0x10;

            string strData;
            string strVisionox = System.Windows.Forms.Application.StartupPath + "/ILI8818_gamma_page" + nPage.ToString("X2") + "_" + (tGammaParam.fTargetLv).ToString() + "nits_visionox.txt";
            string strILI = System.Windows.Forms.Application.StartupPath + "/ILI8818_gamma_page" + nPage.ToString("X2") + "_" + (tGammaParam.fTargetLv).ToString() + "nits_ili.txt";
            StreamWriter swVisionox = new StreamWriter(strVisionox);
            StreamWriter swILI = new StreamWriter(strILI);

            //Visionox format
            NumericUpDown[] NUMR = new NumericUpDown[] { num_ILI8818_R0, num_ILI8818_R1, num_ILI8818_R2, num_ILI8818_R3, num_ILI8818_R4, num_ILI8818_R5, num_ILI8818_R6, num_ILI8818_R7, num_ILI8818_R8, num_ILI8818_R9, num_ILI8818_R10, num_ILI8818_R11, num_ILI8818_R12, num_ILI8818_R13, num_ILI8818_R14, num_ILI8818_R15, num_ILI8818_R16, num_ILI8818_R17, num_ILI8818_R18, num_ILI8818_R19, num_ILI8818_R20, num_ILI8818_R21, num_ILI8818_R22, num_ILI8818_R23 };
            NumericUpDown[] NUMG = new NumericUpDown[] { num_ILI8818_G0, num_ILI8818_G1, num_ILI8818_G2, num_ILI8818_G3, num_ILI8818_G4, num_ILI8818_G5, num_ILI8818_G6, num_ILI8818_G7, num_ILI8818_G8, num_ILI8818_G9, num_ILI8818_G10, num_ILI8818_G11, num_ILI8818_G12, num_ILI8818_G13, num_ILI8818_G14, num_ILI8818_G15, num_ILI8818_G16, num_ILI8818_G17, num_ILI8818_G18, num_ILI8818_G19, num_ILI8818_G20, num_ILI8818_G21, num_ILI8818_G22, num_ILI8818_G23 };
            NumericUpDown[] NUMB = new NumericUpDown[] { num_ILI8818_B0, num_ILI8818_B1, num_ILI8818_B2, num_ILI8818_B3, num_ILI8818_B4, num_ILI8818_B5, num_ILI8818_B6, num_ILI8818_B7, num_ILI8818_B8, num_ILI8818_B9, num_ILI8818_B10, num_ILI8818_B11, num_ILI8818_B12, num_ILI8818_B13, num_ILI8818_B14, num_ILI8818_B15, num_ILI8818_B16, num_ILI8818_B17, num_ILI8818_B18, num_ILI8818_B19, num_ILI8818_B20, num_ILI8818_B21, num_ILI8818_B22, num_ILI8818_B23 };

            strData = "FF,78,38," + nPage.ToString("X2");
            swVisionox.WriteLine(strData);
            Addr = 0;
            for (i = 0; i < 72; i++)
            {
                strData = Addr.ToString("X2") + "," + ((nNewGammaIndexTable[i] & 0x0000FF00) >> 8).ToString("X2");
                swVisionox.WriteLine(strData);
                Addr++;

                strData = Addr.ToString("X2") + "," + ((nNewGammaIndexTable[i] & 0x000000FF)).ToString("X2");
                swVisionox.WriteLine(strData);
                Addr++;
            }
            for (i = 0; i < 24; i++)
            {
                //    strData = "R" + i.ToString() + "," + nNewGammaIndexTable[i].ToString("X4") + ",G" + i.ToString() + "," + nNewGammaIndexTable[24 + i].ToString("X4") + ",B" + i.ToString() + "," + nNewGammaIndexTable[48 + i].ToString("X4");
                //    swVisionox.WriteLine(strData);

                NUMR[i].Value = nNewGammaIndexTable[i];
                NUMG[i].Value = nNewGammaIndexTable[i + 24];
                NUMB[i].Value = nNewGammaIndexTable[i + 48];
            }
            swVisionox.WriteLine("FF,78,38,0C");
            strData = nVGMPAddrH.ToString("X2") + "," + ((nVGMPIdx & 0x0000FF00) >> 8).ToString("X2");
            swVisionox.WriteLine(strData);
            strData = nVGMPAddrL.ToString("X2") + "," + ((nVGMPIdx & 0x000000FF)).ToString("X2");
            swVisionox.WriteLine(strData);
            strData = nVGSPAddrH.ToString("X2") + "," + ((nVGSPIdx & 0x0000FF00) >> 8).ToString("X2");
            swVisionox.WriteLine(strData);
            strData = nVGSPAddrL.ToString("X2") + "," + ((nVGSPIdx & 0x000000FF)).ToString("X2");
            swVisionox.WriteLine(strData);

            // ILITek format
            strData = "REGISTER,FF,3,78,38," + nPage.ToString("X2");
            swILI.WriteLine(strData);
            Addr = 0;
            for (i = 0; i < 72; i++)
            {
                strData = "REGISTER," + Addr.ToString("X2") + ",1," + ((nNewGammaIndexTable[i] & 0x0000FF00) >> 8).ToString("X2");
                swILI.WriteLine(strData);
                Addr++;

                strData = "REGISTER," + Addr.ToString("X2") + ",1," + ((nNewGammaIndexTable[i] & 0x000000FF)).ToString("X2");
                swILI.WriteLine(strData);
                Addr++;
            }
            swILI.WriteLine("\nREGISTER,FF,03,78,38,0C");

            strData = "REGISTER," + nVGMPAddrH.ToString("X2") + ",01," + ((nVGMPIdx & 0x0000FF00) >> 8).ToString("X2");
            swILI.WriteLine(strData);
            strData = "REGISTER," + nVGMPAddrL.ToString("X2") + ",01," + ((nVGMPIdx & 0x000000FF)).ToString("X2");
            swILI.WriteLine(strData);
            strData = "REGISTER," + nVGSPAddrH.ToString("X2") + ",01," + ((nVGSPIdx & 0x0000FF00) >> 8).ToString("X2");
            swILI.WriteLine(strData);
            strData = "REGISTER," + nVGSPAddrL.ToString("X2") + ",01," + ((nVGSPIdx & 0x000000FF)).ToString("X2");
            swILI.WriteLine(strData);

            swVisionox.Close();
            swILI.Close();

            frmHelp.textBox1.Text += "Tune Done\r\n";
            frmHelp.textBox1.SelectionStart = frmHelp.textBox1.TextLength;
            frmHelp.textBox1.ScrollToCaret();

            btnTuneGammaAOD.Enabled = true;
        }

        private void btnTuneIR_Click(object sender, EventArgs e)
        {
            string txtbaseClearOriginal;
            string txtMClearOriginal;

            // get value from tool interface
            int nHeight = int.Parse(txtResH.Text);
            int nWidth = int.Parse(txtResW.Text);
            int nNotchHeight = int.Parse(txtNotchH.Text);
            int blkImgSize = int.Parse(txtBlkImgSize.Text);

            float fNormTargetLv = float.Parse(txtNormDefLv.Text);
            float fNormTargetx = float.Parse(txtNormDefx.Text);
            float fNormTargety = float.Parse(txtNormDefy.Text);
            float fNormTolerance = float.Parse(txtNormTolerance.Text);
            float fTargetGamma = float.Parse(txtDefGamma.Text);

            float fHBMTargetLv = float.Parse(txtHBMDefLv.Text);

            //int[] nNewGammaIndexTable = new int[24 * 3];
            //int[] anHBMGammaIndexTable = new int[24 * 3];
            float[] fxyYForTwoBlkRGBW = new float[2 * 4 * 3];
            float[] fxyYForFullRGBW = new float[4 * 3];
            float[] fxyYForR = new float[2 * 3];
            float[] fxyYForBlkRGB = new float[3 * 3];
            float[] fPara3Lut = new float[4 * 9];
            float[] fxyYFull = new float[3];
            float[] fxyYTarget = new float[3];
            float fIniLv = 0;
            float fInitParaLut = 0;

            int nVGMPAddrH, nVGMPAddrL, nVGSPAddrH, nVGSPAddrL;
            int nGL, nGetLvFlag;
            float fxyTolerance;
            float fLvFull, fLvBlock, fLvFullComp = 0, fLvBlockComp = 0;
            float fx, fy;
            int maxloopcnt, nStop;
            int nPage, Addr, value, i, j;
            int nNorm, nHBMNorm;

            int[] nBlkBoxSize = new int[4];
            int[] nFullBoxSize = new int[4];

            string strRead1;

            tIrParam = new DLLStructure.irParam_t();
            tIrSetting = new DLLStructure.irSetting_t();

            tIrParam.fPara2 = new float[3];
            tIrParam.anGammaPoint = new int[24];

            tIrSetting.fPara1 = new float[3];
            tIrSetting.fPara2 = new float[3];
            tIrSetting.fRatio = new float[3];
            tIrSetting.fHBMRatio = new float[3];
            tIrSetting.fGammaforR = new float[4];
            tIrSetting.fPara3Lut = new float[36];

            //* * * * * * * * * *
            //* step 1 : get Normalize Point from IC or set by manual
            //*          get VGMP / VGSP
            //* * * * * * * * * *
            //switch page 0A, then get value from address (D0, D1) for nNorm ; address (D2, D3) for nHBMNorm
            switchPage(0x0A);
            //nNorm
            txt_Reg_Data_WR.Text = "D0";
            ILI8818_Others_Click(btn_Reg_R, null);
            Delay(250);
            strRead1 = txt_Reg_Data_WR.Text;
            int kki = Convert.ToInt32(strRead1.Substring(strRead1.Length - 2), 16);
            int valuekki = (kki & 0x03) * 256;
            txt_Reg_Data_WR.Text = "D1";
            ILI8818_Others_Click(btn_Reg_R, null);
            Delay(250);
            strRead1 = txt_Reg_Data_WR.Text;
            kki = Convert.ToInt32(strRead1.Substring(strRead1.Length - 2), 16);
            nNorm = (valuekki + kki) / 4;

            //nHBMNorm
            txt_Reg_Data_WR.Text = "D2";
            ILI8818_Others_Click(btn_Reg_R, null);
            Delay(250);
            strRead1 = txt_Reg_Data_WR.Text;
            kki = Convert.ToInt32(strRead1.Substring(strRead1.Length - 2), 16);
            valuekki = (kki & 0x03) * 256;
            txt_Reg_Data_WR.Text = "D3";
            ILI8818_Others_Click(btn_Reg_R, null);
            Delay(250);
            strRead1 = txt_Reg_Data_WR.Text;
            kki = Convert.ToInt32(strRead1.Substring(strRead1.Length - 2), 16);
            nHBMNorm = (valuekki + kki) / 4;

            //nNorm = gnNormPoint;
            //nHBMNorm = gnHBMNormPoint;

            nPage = 0x09;
            nVGMPAddrH = 0x90 + (nPage - 0x09) * 4;
            nVGMPAddrL = 0x91 + (nPage - 0x09) * 4;
            nVGSPAddrH = 0x92 + (nPage - 0x09) * 4;
            nVGSPAddrL = 0x93 + (nPage - 0x09) * 4;
            if (txtNorm1VGMP.Text == "0" || txtNorm1VGSP.Text == "0")
            {
                tIrParam.fVGMP = readVGP(nVGMPAddrH, nVGMPAddrL);
                tIrParam.fVGSP = readVGP(nVGSPAddrH, nVGSPAddrL);
            }
            else
            {
                tIrParam.fVGMP = float.Parse(txtNorm1VGMP.Text);
                tIrParam.fVGSP = float.Parse(txtNorm1VGSP.Text);
            }

            //* * * * * * * * * *
            //* step 2 : set parameters
            //* * * * * * * * * *
            tIrParam.fPara2[0] = tIrParam.fPara2[1] = tIrParam.fPara2[2] = -1;
            tIrParam.nHighGray = 255;
            tIrParam.nLowGray = 160;
            tIrParam.nColorSel = 0;
            tIrParam.nSPRType = 0;
            tIrParam.nCompGL = 0;

            tIrParam.nHeight = nHeight;
            tIrParam.nWidth = nWidth;
            tIrParam.nblkImgSize = blkImgSize;
            tIrParam.nNotchHeight = nNotchHeight;

            tIrParam.fTargetx = fNormTargetx;
            tIrParam.fTargety = fNormTargety;
            tIrParam.fTargetGamma = fTargetGamma;
            tIrParam.fTolerance = fNormTolerance;

            tIrParam.fTargetLv = fNormTargetLv;
            tIrParam.fHBMTargetLv = fHBMTargetLv;

            tIrParam.nNorPoint = nNorm;
            tIrParam.nHBMNorPoint = nHBMNorm;

            //get gamma bonding point from IC or set by manual
            int nGammaPointNum = 24;
            tIrParam.nGammaPointNum = nGammaPointNum;
            tIrParam.anGammaPoint = new int[24];
            //tIrParam.anGammaPoint = new int[24] {0, 4, 12, 20, 28, 32, 36, 40, 44, 52, 84, 92, 112, 144, 176,
            //                                      212, 340, 360, 616, 748, 812, 828, 956, 1020};

            StopTune = false;
            btnTuneIR.Enabled = false;

            //set debug mode
            setDbgMode(1);

            // 讀取對應到nPage的24個綁點的RGB gamma index
            if (nNewGammaIndexTable[23] == 0)
            {
                SetFullPara(0, 0, 0);
                ReadAllGamma(nPage, nNewGammaIndexTable);
                for (int zzz = 0; zzz < 24; zzz++)
                {
                    tIrParam.anGammaPoint[zzz] = nNewGammaIndexTable[zzz];
                }
            }

            // Read initial lut value
            if (gnLutParam == 0)
            {
                //switch to Page 0B
                //switchPage(0x0B);
                // get value of address (B2, B3) -> fInitParaLut
                switchPage(0x0B);

                txt_Reg_Data_WR.Text = "B2";
                ILI8818_Others_Click(btn_Reg_R, null);
                Delay(250);
                strRead1 = txt_Reg_Data_WR.Text;
                i = Convert.ToInt32(strRead1.Substring(strRead1.Length - 2), 16);

                //i = retRegData;
                txt_Reg_Data_WR.Text = "B3";
                ILI8818_Others_Click(btn_Reg_R, null);
                Delay(250);
                strRead1 = txt_Reg_Data_WR.Text;
                j = Convert.ToInt32(strRead1.Substring(strRead1.Length - 2), 16);
                //j = retRegData;
                fInitParaLut = ((i & 0x07) * 256 + j) / 8.0f;
            }
            else
            {
                fInitParaLut = gnLutParam / 8.0f;
            }

            fPara3Lut[0] = 1024;
            fPara3Lut[1] = 896;
            fPara3Lut[2] = 768;
            fPara3Lut[3] = 640;
            fPara3Lut[4] = 512;
            fPara3Lut[5] = 384;
            fPara3Lut[6] = 256;
            fPara3Lut[7] = 128;
            fPara3Lut[8] = 0;
            fPara3Lut[9] = fInitParaLut;

            //* * * * * * * * * *
            //* step 3 : set coordinate of corner for tuning pattern
            //* * * * * * * * * *
            nFullBoxSize[0] = 0;
            nFullBoxSize[1] = nNotchHeight;
            nFullBoxSize[2] = nWidth;
            nFullBoxSize[3] = nHeight - nNotchHeight;

            nBlkBoxSize[0] = (nWidth - blkImgSize) / 2;
            nBlkBoxSize[1] = (nHeight - blkImgSize) / 2;
            nBlkBoxSize[2] = (nWidth + blkImgSize) / 2;
            nBlkBoxSize[3] = (nHeight + blkImgSize) / 2;

            //* * * * * * * * * *
            //* step 4 : function call to set parameter
            //* * * * * * * * * *
            irSetParameter(ref tIrParam);

            //* * * * * * * * * *
            //* step 5 : set IR default settings
            //* * * * * * * * * *
            setIRDefaultSetting(nHeight, nWidth);

            //* * * * * * * * * *
            //* step 6 : show bist mode W 255 block pattern and measure its luminance for initial Lv
            //* * * * * * * * * *
            SetBlkPara(255, 255, 255, nBlkBoxSize[0], nBlkBoxSize[1], nBlkBoxSize[2], nBlkBoxSize[3]);
            StartBistMode();
            GetCAData(out fx, out fy, out fIniLv);

            //* * * * * * * * * *
            //* step 7 : show bist mode specific patterns and measure their luminance
            //* * * * * * * * * *
            frmHelp.textBox1.Text += "Show IR Pattern\r\n";
            frmHelp.textBox1.SelectionStart = frmHelp.textBox1.TextLength;
            frmHelp.textBox1.ScrollToCaret();

            for (i = 0; i < 24; i++)
            {
                fxyYForTwoBlkRGBW[i] = 0;
            }
            for (i = 0; i < 12; i++)
            {
                fxyYForFullRGBW[i] = 0;
            }
            for (i = 0; i < 6; i++)
            {
                fxyYForR[i] = 0;
            }

            SetBlkPara(255, 0, 0, nFullBoxSize[0], nBlkBoxSize[1], nFullBoxSize[2], nFullBoxSize[3]);
            GetCAData(out fxyYForR[0], out fxyYForR[1], out fxyYForR[2]);

            SetBlkPara(255, 0, 0, nFullBoxSize[0], nFullBoxSize[1], nFullBoxSize[2], nBlkBoxSize[3]);
            GetCAData(out fxyYForR[3], out fxyYForR[4], out fxyYForR[5]);

            //enable IR
            enableIR();

            nGL = tIrParam.nHighGray;
            SetBlkPara(nGL, 0, 0, nBlkBoxSize[0], nBlkBoxSize[1], nBlkBoxSize[2], nBlkBoxSize[3]);
            GetCAData(out fxyYForTwoBlkRGBW[0], out fxyYForTwoBlkRGBW[1], out fxyYForTwoBlkRGBW[2]);

            SetBlkPara(0, nGL, 0, nBlkBoxSize[0], nBlkBoxSize[1], nBlkBoxSize[2], nBlkBoxSize[3]);
            GetCAData(out fxyYForTwoBlkRGBW[3], out fxyYForTwoBlkRGBW[4], out fxyYForTwoBlkRGBW[5]);

            SetBlkPara(0, 0, nGL, nBlkBoxSize[0], nBlkBoxSize[1], nBlkBoxSize[2], nBlkBoxSize[3]);
            GetCAData(out fxyYForTwoBlkRGBW[6], out fxyYForTwoBlkRGBW[7], out fxyYForTwoBlkRGBW[8]);

            SetBlkPara(nGL, nGL, nGL, nBlkBoxSize[0], nBlkBoxSize[1], nBlkBoxSize[2], nBlkBoxSize[3]);
            GetCAData(out fxyYForTwoBlkRGBW[9], out fxyYForTwoBlkRGBW[10], out fxyYForTwoBlkRGBW[11]);

            nGL = tIrParam.nLowGray;
            SetBlkPara(nGL, 0, 0, nBlkBoxSize[0], nBlkBoxSize[1], nBlkBoxSize[2], nBlkBoxSize[3]);
            GetCAData(out fxyYForTwoBlkRGBW[12], out fxyYForTwoBlkRGBW[13], out fxyYForTwoBlkRGBW[14]);

            SetBlkPara(0, nGL, 0, nBlkBoxSize[0], nBlkBoxSize[1], nBlkBoxSize[2], nBlkBoxSize[3]);
            GetCAData(out fxyYForTwoBlkRGBW[15], out fxyYForTwoBlkRGBW[16], out fxyYForTwoBlkRGBW[17]);

            SetBlkPara(0, 0, nGL, nBlkBoxSize[0], nBlkBoxSize[1], nBlkBoxSize[2], nBlkBoxSize[3]);
            GetCAData(out fxyYForTwoBlkRGBW[18], out fxyYForTwoBlkRGBW[19], out fxyYForTwoBlkRGBW[20]);

            SetBlkPara(nGL, nGL, nGL, nBlkBoxSize[0], nBlkBoxSize[1], nBlkBoxSize[2], nBlkBoxSize[3]);
            GetCAData(out fxyYForTwoBlkRGBW[21], out fxyYForTwoBlkRGBW[22], out fxyYForTwoBlkRGBW[23]);

            nGL = tIrParam.nHighGray;
            SetFullPara(nGL, 0, 0);
            GetCAData(out fxyYForFullRGBW[0], out fxyYForFullRGBW[1], out fxyYForFullRGBW[2]);

            SetFullPara(0, nGL, 0);
            GetCAData(out fxyYForFullRGBW[3], out fxyYForFullRGBW[4], out fxyYForFullRGBW[5]);

            SetFullPara(0, 0, nGL);
            GetCAData(out fxyYForFullRGBW[6], out fxyYForFullRGBW[7], out fxyYForFullRGBW[8]);

            SetFullPara(nGL, nGL, nGL);
            GetCAData(out fxyYForFullRGBW[9], out fxyYForFullRGBW[10], out fxyYForFullRGBW[11]);

            //* * * * * * * * * *
            //* step 8 : Calculate IR settings
            //* * * * * * * * * *
            frmHelp.textBox1.Text += "Calculate IR settings\r\n";
            frmHelp.textBox1.SelectionStart = frmHelp.textBox1.TextLength;
            frmHelp.textBox1.ScrollToCaret();

            irCalSetting(nNewGammaIndexTable, fPara3Lut, fxyYForTwoBlkRGBW, fxyYForFullRGBW, fxyYForR);
            irGetSetting(ref tIrSetting);

            //* * * * * * * * * *
            //* step 9 : Write IR settings into IC
            //* * * * * * * * * *
            setIRSetting(tIrSetting);

            //* * * * * * * * * *
            //* step 10 : Fine tune IR settings
            //* * * * * * * * * *
            frmHelp.textBox1.Text += "Fine tune IR settings\r\n";
            frmHelp.textBox1.SelectionStart = frmHelp.textBox1.TextLength;
            frmHelp.textBox1.ScrollToCaret();

            fxyTolerance = 1.0f;
            fLvFull = fxyYForFullRGBW[11];
            fLvBlock = fxyYForTwoBlkRGBW[11];

            maxloopcnt = 10;
            nStop = 0;
            do
            {
                // switch to IR page
                switchPage(0x0B);

                Addr = 0x99;
                cmdstr = "";
                for (i = 0; i < 3; i++)
                {
                    value = (int)(tIrSetting.fPara2[i] * 64);
                    //REGISTER,Addr+i,1,value;
                    cmdstr = cmdstr + ";" + (Addr + i).ToString("X2") + "," + value.ToString("X2");
                }

                cmdstr = cmdstr.Replace(";", "\r\n");
                frmHelp.txtProcessDrivercode(cmdstr, out txtbaseClearOriginal, out txtMClearOriginal);
                //MainForm.SendCmd(0);    //Write by Low Speed
                frmHelp.SendCmd(4);    //Write by High Speed

                SetBlkPara(255, 255, 255, nFullBoxSize[0], nFullBoxSize[1], nFullBoxSize[2], nFullBoxSize[3]);
                GetCAData(out fx, out fy, out fLvFullComp);

                SetBlkPara(255, 255, 255, nBlkBoxSize[0], nBlkBoxSize[1], nBlkBoxSize[2], nBlkBoxSize[3]);
                GetCAData(out fx, out fy, out fLvBlockComp);

                nStop = irUpdatePara(nNewGammaIndexTable, fLvFull, fLvBlock, fLvFullComp, fLvBlockComp, fxyTolerance);
                irGetSetting(ref tIrSetting);

                if (StopTune)
                {
                    StopBistMode();
                    disableIR();
                    btnTuneIR.Enabled = true;
                    return;
                }
            } while (((--maxloopcnt) > 0) && (nStop == 0));

            nGetLvFlag = 0;
            fxyTolerance = 0.001f;
            fxyYTarget[0] = fxyYForTwoBlkRGBW[9];
            fxyYTarget[1] = fxyYForTwoBlkRGBW[10];

            for (i = 0; i < 3; i++)
            {
                fxyYForBlkRGB[i * 3 + 0] = fxyYForTwoBlkRGBW[i * 3 + 0];
                fxyYForBlkRGB[i * 3 + 1] = fxyYForTwoBlkRGBW[i * 3 + 1];
                fxyYForBlkRGB[i * 3 + 2] = fxyYForTwoBlkRGBW[i * 3 + 2];
            }

            maxloopcnt = 10;
            nStop = 0;
            do
            {
                // switch to IR page
                switchPage(0x0B);

                Addr = 0x9C;
                cmdstr = "";
                for (i = 0; i < 3; i++)
                {
                    value = (int)(tIrSetting.fRatio[i] * 64);
                    //REGISTER,Addr+i,1,value;
                    cmdstr = cmdstr + ";" + (Addr + i).ToString("X2") + "," + value.ToString("X2");
                }

                cmdstr = cmdstr.Replace(";", "\r\n");
                frmHelp.txtProcessDrivercode(cmdstr, out txtbaseClearOriginal, out txtMClearOriginal);
                //MainForm.SendCmd(0);    //Write by Low Speed
                frmHelp.SendCmd(4);    //Write by High Speed

                SetBlkPara(255, 255, 255, nFullBoxSize[0], nFullBoxSize[1], nFullBoxSize[2], nFullBoxSize[3]);
                GetCAData(out fxyYFull[0], out fxyYFull[1], out fxyYFull[2]);

                if (nGetLvFlag == 0)
                {
                    nGetLvFlag = 1;
                    fxyYTarget[2] = fxyYFull[2];
                }
                nStop = irCalRatio(nNewGammaIndexTable, fxyYForBlkRGB, fxyYTarget, fxyYFull, fxyTolerance, 0);
                irGetSetting(ref tIrSetting);

                if (StopTune)
                {
                    StopBistMode();
                    disableIR();
                    btnTuneIR.Enabled = true;
                    return;
                }
            } while (((--maxloopcnt) > 0) && (nStop == 0));

            // = = = = = = = = = = = = = = = = = = = = =
            // Tune HBM Gamma
            // = = = = = = = = = = = = = = = = = = = = =
            int nTunePointNum = 24;
            int[] nTuneIndex = new int[24] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23 };

            float fRecordLv = fIniLv;
            float[] afMeasuredLv = new float[3];
            float[] fHBM_VGP = new float[2];
            //char Nor_Num, HBM_Sel;
            int isShowBlkImg = 0;
            int nHBMpageSel;
            int nTuneNum;

            //* * * * * * * * * *
            //* step 12 : set HBM gamma page
            //* * * * * * * * * *
            //REGISTER,FF,3,78,38,09;  
            //Nor_Num = READREGISTER,95,1;
            //Nor_Num = (Nor_Num & 0x70) >> 4;
            //HBM_Sel = READREGISTER,97,1;
            //HBM_Sel = (HBM_Sel & 0xC0) >> 6;
            nHBMpageSel = 0x0D; //0x09 + (Nor_Num - 1) + (HBM_Sel + 1);
            nVGSPAddrH = 0xA2;
            nVGSPAddrL = 0xA3;

            //disable IR
            disableIR();

            frmHelp.textBox1.Text += "Calculate HBM Gamma Index\r\n";
            frmHelp.textBox1.SelectionStart = frmHelp.textBox1.TextLength;
            frmHelp.textBox1.ScrollToCaret();

            SetBlkPara(255, 255, 255, nBlkBoxSize[0], nBlkBoxSize[1], nBlkBoxSize[2], nBlkBoxSize[3]);

            for (i = 0; i < 3; i++)
            {
                afMeasuredLv[i] = 0;
                fxyYFull[i] = 0;
            }

            maxloopcnt = 10;
            nStop = 0;
            nTuneNum = 5;
            int nHBMScale = 1024;

            do
            {
                nStop = irGenHBMGamma(nNewGammaIndexTable, anHBMGammaIndexTable, fRecordLv, afMeasuredLv, fxyYFull);
                irGetSetting(ref tIrSetting);

                fHBM_VGP[0] = tIrSetting.fHBMVGMP;
                fHBM_VGP[1] = tIrSetting.fHBMVGSP;

                writeVGP(nVGSPAddrH, nVGSPAddrL, fHBM_VGP[1]);

                //txtHBMVGSP.Text = tIrSetting.fHBMVGSP.ToString();

                if (maxloopcnt == 10)
                {
                    WriteAllGamma(nHBMpageSel, anHBMGammaIndexTable);

                    // set HBM scale
                    //REGISTER,FF,3,78,38,0A; 
                    //REGISTER,DC,1,(tIrSetting.HBMscale & 0x0000FF00)>>8;
                    //REGISTER,DD,1,(tIrSetting.HBMscale & 0x000000FF);
                    nHBMScale = Convert.ToInt32((fHBMTargetLv * Math.Pow(255.0 / nHBMNorm, fTargetGamma)) / (fNormTargetLv * Math.Pow(255.0 / nNorm, fTargetGamma)) * 1024 + 0.5);

                    cmdstr = "FF,78,38,0A";
                    cmdstr = cmdstr + ";DC," + ((nHBMScale & 0x0000FF00) >> 8).ToString("X2");
                    cmdstr = cmdstr + ";DD," + ((nHBMScale & 0x000000FF)).ToString("X2");

                    cmdstr = cmdstr.Replace(";", "\r\n");
                    frmHelp.txtProcessDrivercode(cmdstr, out txtbaseClearOriginal, out txtMClearOriginal);
                    //MainForm.SendCmd(0);    //Write by Low Speed
                    frmHelp.SendCmd(4);    //Write by High Speed

                    //switch to HBM
                    switchMode(0xE4);
                }
                else
                {
                    WriteSomeGammaIndex(nHBMpageSel, anHBMGammaIndexTable, nTuneNum);
                }

                if (nStop == 0)
                {
                    if (isShowBlkImg == 0)
                    {
                        //disable IR and show bist mode W255 block pattern
                        disableIR();

                        SetBlkPara(255, 255, 255, nBlkBoxSize[0], nBlkBoxSize[1], nBlkBoxSize[2], nBlkBoxSize[3]);
                        isShowBlkImg = 1;
                    }

                    //measure luminance of last 3 gamma index
                    for (i = 3; i > 0; i--)
                    {
                        WriteGammaOfLastOnePoint(nHBMpageSel,
                            anHBMGammaIndexTable[nTuneIndex[nTunePointNum - i]],
                            anHBMGammaIndexTable[nGammaPointNum + nTuneIndex[nTunePointNum - i]],
                            anHBMGammaIndexTable[nGammaPointNum * 2 + nTuneIndex[nTunePointNum - i]]);
                        GetCAData(out fx, out fy, out afMeasuredLv[3 - i]);
                    }
                    for (i = 0; i < 3; i++)
                    {
                        fxyYFull[i] = 0;
                    }
                }
                else
                {
                    WriteSomeGammaIndex(nHBMpageSel, anHBMGammaIndexTable, nTuneNum);

                    //enable IR
                    enableIR();

                    //show bist mode specific W255 full pattern and measure its x, y, luminance
                    SetBlkPara(255, 255, 255, nFullBoxSize[0], nFullBoxSize[1], nFullBoxSize[2], nFullBoxSize[3]);
                    GetCAData(out fxyYFull[0], out fxyYFull[1], out fxyYFull[2]);

                    float fErrLv = (fxyYFull[2] > fHBMTargetLv) ? (fHBMTargetLv * 0.005f) : (1.0f);
                    if (Math.Abs(fxyYFull[2] - fHBMTargetLv) > fErrLv)
                    {
                        for (i = 0; i < 3; i++)
                        {
                            afMeasuredLv[i] = 0;
                        }
                        nStop = 0;
                        maxloopcnt = 11;
                        isShowBlkImg = 0;
                    }
                }

                if (StopTune)
                {
                    StopBistMode();
                    disableIR();
                    btnTuneIR.Enabled = true;
                    return;
                }
            } while (((--maxloopcnt) > 0) && (nStop == 0));

            WriteAllGamma(nHBMpageSel, anHBMGammaIndexTable);

            //enable IR
            enableIR();

            nGetLvFlag = 0;
            fxyTolerance = 0.001f;
            fxyYTarget[0] = fxyYForTwoBlkRGBW[9];
            fxyYTarget[1] = fxyYForTwoBlkRGBW[10];

            for (i = 0; i < 3; i++)
            {
                fxyYForBlkRGB[i * 3 + 0] = fxyYForTwoBlkRGBW[i * 3 + 0];
                fxyYForBlkRGB[i * 3 + 1] = fxyYForTwoBlkRGBW[i * 3 + 1];
                fxyYForBlkRGB[i * 3 + 2] = fxyYForTwoBlkRGBW[i * 3 + 2];
            }

            maxloopcnt = 10;
            nStop = 0;
            do
            {
                // switch to IR page
                switchPage(0x0B);

                Addr = 0x9F;
                cmdstr = "";
                for (i = 0; i < 3; i++)
                {
                    value = (int)(tIrSetting.fHBMRatio[i] * 64);
                    //REGISTER,Addr+i,1,value;
                    cmdstr = cmdstr + ";" + (Addr + i).ToString("X2") + "," + value.ToString("X2");
                }

                cmdstr = cmdstr.Replace(";", "\r\n");
                frmHelp.txtProcessDrivercode(cmdstr, out txtbaseClearOriginal, out txtMClearOriginal);
                //MainForm.SendCmd(0);    //Write by Low Speed
                frmHelp.SendCmd(4);    //Write by High Speed

                if (maxloopcnt == 10)
                {
                    SetBlkPara(255, 255, 255, nFullBoxSize[0], nFullBoxSize[1], nFullBoxSize[2], nFullBoxSize[3]);
                }
                GetCAData(out fxyYFull[0], out fxyYFull[1], out fxyYFull[2]);

                if (nGetLvFlag == 0)
                {
                    nGetLvFlag = 1;
                    fxyYTarget[2] = fxyYFull[2];
                }

                nStop = irCalRatio(anHBMGammaIndexTable, fxyYForBlkRGB, fxyYTarget, fxyYFull, fxyTolerance, 1);
                if (nStop == 0)
                {
                    irGetSetting(ref tIrSetting);
                }

                if (StopTune)
                {
                    StopBistMode();
                    disableIR();
                    btnTuneIR.Enabled = true;
                    return;
                }
            } while (((--maxloopcnt) > 0) && (nStop == 0));

            // return normal mode
            switchMode(0x24);

            StopBistMode();
            //frmHelp.OLED_Show_Click(frmHelp.btnblack, null);
            frmHelp.GrayShow(0, 0, 0);
            //irSaveSetting();
            //* * * * * * * * * *
            // step 14: save all settings into file
            //* * * * * * * * * *
            int nVGMPIdx, nVGSPIdx;

            string strData;
            string strVisionox = System.Windows.Forms.Application.StartupPath + "/ILI8818_gamma_ir_settings_visionox.txt";
            string strILI = System.Windows.Forms.Application.StartupPath + "/ILI8818_gamma_ir_settings_ili.txt";
            StreamWriter swVisionox = new StreamWriter(strVisionox);
            StreamWriter swILI = new StreamWriter(strILI);

            // Visionox format
            strData = "FF,78,38," + nPage.ToString("X2");
            swVisionox.WriteLine(strData);
            Addr = 0;
            for (i = 0; i < 72; i++)
            {
                strData = Addr.ToString("X2") + "," + ((nNewGammaIndexTable[i] & 0x0000FF00) >> 8).ToString("X2");
                swVisionox.WriteLine(strData);
                Addr++;
                strData = Addr.ToString("X2") + "," + ((nNewGammaIndexTable[i] & 0x000000FF)).ToString("X2");
                swVisionox.WriteLine(strData);
                Addr++;
            }

            strData = "FF,78,38," + nHBMpageSel.ToString("X2");
            swVisionox.WriteLine(strData);
            Addr = 0;
            for (i = 0; i < 72; i++)
            {
                strData = Addr.ToString("X2") + "," + ((anHBMGammaIndexTable[i] & 0x0000FF00) >> 8).ToString("X2");
                swVisionox.WriteLine(strData);
                Addr++;
                strData = Addr.ToString("X2") + "," + ((anHBMGammaIndexTable[i] & 0x000000FF)).ToString("X2");
                swVisionox.WriteLine(strData);
                Addr++;
            }

            swVisionox.WriteLine("FF,78,38,0A");
            strData = "D0," + (((tIrSetting.nNorPoint * 4) & 0x0000FF00) >> 8).ToString("X2");
            swVisionox.WriteLine(strData);
            strData = "D1," + (((tIrSetting.nNorPoint * 4) & 0x000000FF)).ToString("X2");
            swVisionox.WriteLine(strData);
            strData = "D2," + (((tIrSetting.nHBMNorPoint * 4) & 0x0000FF00) >> 8).ToString("X2");
            swVisionox.WriteLine(strData);
            strData = "D3," + (((tIrSetting.nHBMNorPoint * 4) & 0x000000FF)).ToString("X2");
            swVisionox.WriteLine(strData);
            strData = "DC," + ((tIrSetting.HBMscale & 0x0000FF00) >> 8).ToString("X2");
            swVisionox.WriteLine(strData);
            strData = "DD," + ((tIrSetting.HBMscale & 0x000000FF)).ToString("X2");
            swVisionox.WriteLine(strData);

            swVisionox.WriteLine("FF,78,38,0B");
            swVisionox.WriteLine("90,A4");
            strData = "91," + ((nHeight & 0x0000FF00) >> 8).ToString("X2");
            swVisionox.WriteLine(strData);
            strData = "92," + ((nHeight & 0x000000FF)).ToString("X2");
            swVisionox.WriteLine(strData);
            strData = "93," + ((nWidth & 0x0000FF00) >> 8).ToString("X2");
            swVisionox.WriteLine(strData);
            strData = "94," + ((nWidth & 0x000000FF)).ToString("X2");
            swVisionox.WriteLine(strData);

            Addr = 0x95;
            for (i = 0; i < 3; i++)
            {
                value = (int)(tIrSetting.fPara1[0] * 64.0f);
                strData = (Addr + i).ToString("X2") + "," + value.ToString("X2");
                swVisionox.WriteLine(strData);
            }
            Addr = 0x99;
            for (i = 0; i < 3; i++)
            {
                value = (int)(tIrSetting.fPara2[0] * 64.0f);
                strData = (Addr + i).ToString("X2") + "," + value.ToString("X2");
                swVisionox.WriteLine(strData);
            }
            Addr = 0x9C;
            for (i = 0; i < 3; i++)
            {
                value = (int)(tIrSetting.fRatio[i] * 64.0f);
                strData = (Addr + i).ToString("X2") + "," + value.ToString("X2");
                swVisionox.WriteLine(strData);
            }
            Addr = 0x9F;
            for (i = 0; i < 3; i++)
            {
                value = (int)(tIrSetting.fHBMRatio[i] * 64.0f);
                strData = (Addr + i).ToString("X2") + "," + value.ToString("X2");
                swVisionox.WriteLine(strData);
            }

            Addr = 0xA2;
            for (i = 0; i < 9; i++)
            {
                value = (int)(tIrSetting.fPara3Lut[17 - i] * 8.0f);
                strData = (Addr + (i * 2)).ToString("X2") + "," + ((value & 0x0000FF00) >> 8).ToString("X2");
                swVisionox.WriteLine(strData);
                strData = (Addr + (i * 2) + 1).ToString("X2") + "," + ((value & 0x000000FF)).ToString("X2");
                swVisionox.WriteLine(strData);
            }
            Addr = 0xB4;
            for (i = 0; i < 9; i++)
            {
                value = (int)(tIrSetting.fPara3Lut[26 - i] * 8.0f);
                strData = (Addr + (i * 2)).ToString("X2") + "," + ((value & 0x0000FF00) >> 8).ToString("X2");
                swVisionox.WriteLine(strData);
                strData = (Addr + (i * 2) + 1).ToString("X2") + "," + ((value & 0x000000FF)).ToString("X2");
                swVisionox.WriteLine(strData);
            }
            Addr = 0xC6;
            for (i = 0; i < 9; i++)
            {
                value = (int)(tIrSetting.fPara3Lut[35 - i] * 8.0f);
                strData = (Addr + (i * 2)).ToString("X2") + "," + ((value & 0x0000FF00) >> 8).ToString("X2");
                swVisionox.WriteLine(strData);
                strData = (Addr + (i * 2) + 1).ToString("X2") + "," + ((value & 0x000000FF)).ToString("X2");
                swVisionox.WriteLine(strData);
            }

            nVGMPIdx = (int)(((tIrSetting.fVGMP - 0.4) / 0.01) + 0.5f) + 0x10;
            nVGSPIdx = (int)(((tIrSetting.fVGSP - 0.4) / 0.01) + 0.5f) + 0x10;

            swVisionox.WriteLine("FF,78,38,0C");
            strData = "90," + ((nVGMPIdx & 0x0000FF00) >> 8).ToString("X2");
            swVisionox.WriteLine(strData);
            strData = "91," + ((nVGMPIdx & 0x000000FF)).ToString("X2");
            swVisionox.WriteLine(strData);
            strData = "92," + ((nVGSPIdx & 0x0000FF00) >> 8).ToString("X2");
            swVisionox.WriteLine(strData);
            strData = "93," + ((nVGSPIdx & 0x000000FF)).ToString("X2");
            swVisionox.WriteLine(strData);

            nVGMPIdx = (int)(((tIrSetting.fHBMVGMP - 0.4) / 0.01) + 0.5f) + 0x10;
            nVGSPIdx = (int)(((tIrSetting.fHBMVGSP - 0.4) / 0.01) + 0.5f) + 0x10;

            strData = "A0," + ((nVGMPIdx & 0x0000FF00) >> 8).ToString("X2");
            swVisionox.WriteLine(strData);
            strData = "A1," + ((nVGMPIdx & 0x000000FF)).ToString("X2");
            swVisionox.WriteLine(strData);
            strData = "A2," + ((nVGSPIdx & 0x0000FF00) >> 8).ToString("X2");
            swVisionox.WriteLine(strData);
            strData = "A3," + ((nVGSPIdx & 0x000000FF)).ToString("X2");
            swVisionox.WriteLine(strData);

            swVisionox.WriteLine("FF,78,38,00");
            swVisionox.WriteLine("95,10");


            // ILITek format
            strData = "REGISTER,FF,3,78,38," + nPage.ToString("X2");
            swILI.WriteLine(strData);
            Addr = 0;
            for (i = 0; i < 72; i++)
            {
                strData = "REGISTER," + Addr.ToString("X2") + ",1," + ((nNewGammaIndexTable[i] & 0x0000FF00) >> 8).ToString("X2");
                swILI.WriteLine(strData);
                Addr++;
                strData = "REGISTER," + Addr.ToString("X2") + ",1," + ((nNewGammaIndexTable[i] & 0x000000FF)).ToString("X2");
                swILI.WriteLine(strData);
                Addr++;
            }

            strData = "REGISTER,FF,3,78,38," + nHBMpageSel.ToString("X2");
            swILI.WriteLine(strData);
            Addr = 0;
            for (i = 0; i < 72; i++)
            {
                strData = "REGISTER," + Addr.ToString("X2") + ",1," + ((anHBMGammaIndexTable[i] & 0x0000FF00) >> 8).ToString("X2");
                swILI.WriteLine(strData);
                Addr++;
                strData = "REGISTER," + Addr.ToString("X2") + ",1," + ((anHBMGammaIndexTable[i] & 0x000000FF)).ToString("X2");
                swILI.WriteLine(strData);
                Addr++;
            }

            swILI.WriteLine("\nREGISTER,FF,3,78,38,0A");
            strData = "REGISTER,D0,1," + (((tIrSetting.nNorPoint * 4) & 0x0000FF00) >> 8).ToString("X2");
            swILI.WriteLine(strData);
            strData = "REGISTER,D1,1," + (((tIrSetting.nNorPoint * 4) & 0x000000FF)).ToString("X2");
            swILI.WriteLine(strData);
            strData = "REGISTER,D2,1," + (((tIrSetting.nHBMNorPoint * 4) & 0x0000FF00) >> 8).ToString("X2");
            swILI.WriteLine(strData);
            strData = "REGISTER,D3,1," + (((tIrSetting.nHBMNorPoint * 4) & 0x000000FF)).ToString("X2");
            swILI.WriteLine(strData);
            strData = "REGISTER,DC,1," + ((tIrSetting.HBMscale & 0x0000FF00) >> 8).ToString("X2");
            swILI.WriteLine(strData);
            strData = "REGISTER,DD,1," + ((tIrSetting.HBMscale & 0x000000FF)).ToString("X2");
            swILI.WriteLine(strData);

            swILI.WriteLine("\nREGISTER,FF,3,78,38,0B");
            swILI.WriteLine("REGISTER,90,1,A4");
            strData = "REGISTER,91,1," + ((nHeight & 0x0000FF00) >> 8).ToString("X2");
            swILI.WriteLine(strData);
            strData = "REGISTER,92,1," + ((nHeight & 0x000000FF)).ToString("X2");
            swILI.WriteLine(strData);
            strData = "REGISTER,93,1," + ((nWidth & 0x0000FF00) >> 8).ToString("X2");
            swILI.WriteLine(strData);
            strData = "REGISTER,94,1," + ((nWidth & 0x000000FF)).ToString("X2");
            swILI.WriteLine(strData);

            Addr = 0x95;
            for (i = 0; i < 3; i++)
            {
                value = (int)(tIrSetting.fPara1[0] * 64.0f);
                strData = "REGISTER," + (Addr + i).ToString("X2") + ",1," + value.ToString("X2");
                swILI.WriteLine(strData);
            }
            Addr = 0x99;
            for (i = 0; i < 3; i++)
            {
                value = (int)(tIrSetting.fPara2[0] * 64.0f);
                strData = "REGISTER," + (Addr + i).ToString("X2") + ",1," + value.ToString("X2");
                swILI.WriteLine(strData);
            }
            Addr = 0x9C;
            for (i = 0; i < 3; i++)
            {
                value = (int)(tIrSetting.fRatio[i] * 64.0f);
                strData = "REGISTER," + (Addr + i).ToString("X2") + ",1," + value.ToString("X2");
                swILI.WriteLine(strData);
            }
            Addr = 0x9F;
            for (i = 0; i < 3; i++)
            {
                value = (int)(tIrSetting.fHBMRatio[i] * 64.0f);
                strData = "REGISTER," + (Addr + i).ToString("X2") + ",1," + value.ToString("X2");
                swILI.WriteLine(strData);
            }

            Addr = 0xA2;
            for (i = 0; i < 9; i++)
            {
                value = (int)(tIrSetting.fPara3Lut[17 - i] * 8.0f);
                strData = "REGISTER," + (Addr + (i * 2)).ToString("X2") + ",1," + ((value & 0x0000FF00) >> 8).ToString("X2");
                swILI.WriteLine(strData);
                strData = "REGISTER," + (Addr + (i * 2) + 1).ToString("X2") + ",1," + ((value & 0x000000FF)).ToString("X2");
                swILI.WriteLine(strData);
            }
            Addr = 0xB4;
            for (i = 0; i < 9; i++)
            {
                value = (int)(tIrSetting.fPara3Lut[26 - i] * 8.0f);
                strData = "REGISTER," + (Addr + (i * 2)).ToString("X2") + ",1," + ((value & 0x0000FF00) >> 8).ToString("X2");
                swILI.WriteLine(strData);
                strData = "REGISTER," + (Addr + (i * 2) + 1).ToString("X2") + ",1," + ((value & 0x000000FF)).ToString("X2");
                swILI.WriteLine(strData);
            }
            Addr = 0xC6;
            for (i = 0; i < 9; i++)
            {
                value = (int)(tIrSetting.fPara3Lut[35 - i] * 8.0f);
                strData = "REGISTER," + (Addr + (i * 2)).ToString("X2") + ",1," + ((value & 0x0000FF00) >> 8).ToString("X2");
                swILI.WriteLine(strData);
                strData = "REGISTER," + (Addr + (i * 2) + 1).ToString("X2") + ",1," + ((value & 0x000000FF)).ToString("X2");
                swILI.WriteLine(strData);
            }

            nVGMPIdx = (int)(((tIrSetting.fVGMP - 0.4) / 0.01) + 0.5f) + 0x10;
            nVGSPIdx = (int)(((tIrSetting.fVGSP - 0.4) / 0.01) + 0.5f) + 0x10;

            swILI.WriteLine("\nREGISTER,FF,3,78,38,0C");
            strData = "REGISTER,90,1," + ((nVGMPIdx & 0x0000FF00) >> 8).ToString("X2");
            swILI.WriteLine(strData);
            strData = "REGISTER,91,1," + ((nVGMPIdx & 0x000000FF)).ToString("X2");
            swILI.WriteLine(strData);
            strData = "REGISTER,92,1," + ((nVGSPIdx & 0x0000FF00) >> 8).ToString("X2");
            swILI.WriteLine(strData);
            strData = "REGISTER,93,1," + ((nVGSPIdx & 0x000000FF)).ToString("X2");
            swILI.WriteLine(strData);

            nVGMPIdx = (int)(((tIrSetting.fHBMVGMP - 0.4) / 0.01) + 0.5f) + 0x10;
            nVGSPIdx = (int)(((tIrSetting.fHBMVGSP - 0.4) / 0.01) + 0.5f) + 0x10;

            strData = "REGISTER,A0,1," + ((nVGMPIdx & 0x0000FF00) >> 8).ToString("X2");
            swILI.WriteLine(strData);
            strData = "REGISTER,A1,1," + ((nVGMPIdx & 0x000000FF)).ToString("X2");
            swILI.WriteLine(strData);
            strData = "REGISTER,A2,1," + ((nVGSPIdx & 0x0000FF00) >> 8).ToString("X2");
            swILI.WriteLine(strData);
            strData = "REGISTER,A3,1," + ((nVGSPIdx & 0x000000FF)).ToString("X2");
            swILI.WriteLine(strData);

            swILI.WriteLine("\nREGISTER,FF,3,78,38,00");
            swILI.WriteLine("REGISTER,95,1,10");

            swVisionox.Close();
            swILI.Close();

            frmHelp.textBox1.Text += "Tune Done\r\n";
            frmHelp.textBox1.SelectionStart = frmHelp.textBox1.TextLength;
            frmHelp.textBox1.ScrollToCaret();

            btnTuneIR.Enabled = true;
        }

        private void btnTuneCM_Click(object sender, EventArgs e)
        {
            string txtbaseClearOriginal;
            string txtMClearOriginal;

            // get value from tool interface
            int nHeight = int.Parse(txtResH.Text);
            int nWidth = int.Parse(txtResW.Text);
            int blkImgSize = int.Parse(txtBlkImgSize.Text);

            int[,] rgbGL = new int[4, 3];
            double[,] xy_tar = new double[4, 2];
            double[,] RGBWxy_ori = new double[4, 2];
            int[,] CMCode = new int[3, 3];
            int i, j, k, Addr, value;
            float fx, fy, fLv;

            int[] nBlkBoxSize = new int[4];

            btnTuneCM.Enabled = false;

            string strData;
            string strVisionox = System.Windows.Forms.Application.StartupPath + "/ILI8818_cm_settings_visionox.txt";
            StreamWriter swVisionox = new StreamWriter(strVisionox);

            //* * * * * * * * * *
            //* step 1 : set coordinate of corner for tuning pattern
            //* * * * * * * * * *
            nBlkBoxSize[0] = (nWidth - blkImgSize) / 2;
            nBlkBoxSize[1] = (nHeight - blkImgSize) / 2;
            nBlkBoxSize[2] = (nWidth + blkImgSize) / 2;
            nBlkBoxSize[3] = (nHeight + blkImgSize) / 2;

            //* * * * * * * * * *
            //* step 2 : set RGBW gray
            //* * * * * * * * * *
            rgbGL[0, 0] = 255;
            rgbGL[0, 1] = 0;
            rgbGL[0, 2] = 0;
            rgbGL[1, 0] = 0;
            rgbGL[1, 1] = 255;
            rgbGL[1, 2] = 0;
            rgbGL[2, 0] = 0;
            rgbGL[2, 1] = 0;
            rgbGL[2, 2] = 255;
            rgbGL[3, 0] = 255;
            rgbGL[3, 1] = 255;
            rgbGL[3, 2] = 255;

            //* * * * * * * * * *
            //* step 3 : Disable IR function
            //* * * * * * * * * *
            disableIR();

            //* * * * * * * * * *
            //* step 4 : show bist mode RGBW 255 block patterns and measure their x, y
            //* * * * * * * * * *
            SetBlkPara(255, 0, 0, nBlkBoxSize[0], nBlkBoxSize[1], nBlkBoxSize[2], nBlkBoxSize[3]);
            StartBistMode();

            GetCAData(out fx, out fy, out fLv);
            RGBWxy_ori[0, 0] = fx;
            RGBWxy_ori[0, 1] = fy;

            SetBlkPara(0, 255, 0, nBlkBoxSize[0], nBlkBoxSize[1], nBlkBoxSize[2], nBlkBoxSize[3]);
            GetCAData(out fx, out fy, out fLv);
            RGBWxy_ori[1, 0] = fx;
            RGBWxy_ori[1, 1] = fy;

            SetBlkPara(0, 0, 255, nBlkBoxSize[0], nBlkBoxSize[1], nBlkBoxSize[2], nBlkBoxSize[3]);
            GetCAData(out fx, out fy, out fLv);
            RGBWxy_ori[2, 0] = fx;
            RGBWxy_ori[2, 1] = fy;

            SetBlkPara(255, 255, 255, nBlkBoxSize[0], nBlkBoxSize[1], nBlkBoxSize[2], nBlkBoxSize[3]);
            GetCAData(out fx, out fy, out fLv);
            RGBWxy_ori[3, 0] = fx;
            RGBWxy_ori[3, 1] = fy;

            StopBistMode();
            frmHelp.GrayShow(0, 0, 0);

            swVisionox.WriteLine("FF,78,38,13");

            for (k = 0; k < 3; k++)
            {
                // set target x, y of different color space
                if (k == 0)  //sRGB
                {
                    xy_tar[0, 0] = 0.64;
                    xy_tar[0, 1] = 0.33;
                    xy_tar[1, 0] = 0.3;
                    xy_tar[1, 1] = 0.6;
                    xy_tar[2, 0] = 0.15;
                    xy_tar[2, 1] = 0.06;
                    xy_tar[3, 0] = 0.3127;
                    xy_tar[3, 1] = 0.329;
                }
                else if (k == 1) //AdobeRGB
                {
                    xy_tar[0, 0] = 0.64;
                    xy_tar[0, 1] = 0.33;
                    xy_tar[1, 0] = 0.21;
                    xy_tar[1, 1] = 0.71;
                    xy_tar[2, 0] = 0.15;
                    xy_tar[2, 1] = 0.06;
                    xy_tar[3, 0] = 0.3127;
                    xy_tar[3, 1] = 0.329;
                }
                else  //DCI-P3
                {
                    xy_tar[0, 0] = 0.68;
                    xy_tar[0, 1] = 0.32;
                    xy_tar[1, 0] = 0.265;
                    xy_tar[1, 1] = 0.69;
                    xy_tar[2, 0] = 0.15;
                    xy_tar[2, 1] = 0.06;
                    xy_tar[3, 0] = 0.3127;
                    xy_tar[3, 1] = 0.329;
                }

                CRmatrix_v3(CMCode, RGBWxy_ori, rgbGL, xy_tar, 4, 1);

                // switch to CM page
                switchPage(0x13);

                //Write CM Code into IC for different color space group
                if (k == 0)
                {
                    Addr = 0x61;
                }
                else if (k == 1)
                {
                    Addr = 0x79;
                }
                else
                {
                    Addr = 0x91;
                }

                cmdstr = "";
                for (i = 0; i < 3; i++)
                {
                    for (j = 0; j < 3; j++)
                    {
                        value = (CMCode[i, j] > 511) ? 511 : CMCode[i, j];
                        if (value < 0)
                        {
                            value = (value * (-1)) | 0x00008000;
                        }

                        //REGISTER,Addr,1,(value & 0x0000FF00)>>8;
                        strData = Addr.ToString("X2") + "," + ((value & 0x0000FF00) >> 8).ToString("X2");
                        swVisionox.WriteLine(strData);

                        cmdstr = cmdstr + ";" + strData;
                        Addr++;

                        //REGISTER,Addr,1,(value & 0x000000FF);
                        strData = Addr.ToString("X2") + "," + ((value & 0x000000FF)).ToString("X2");
                        swVisionox.WriteLine(strData);

                        cmdstr = cmdstr + ";" + strData;
                        Addr++;
                    }
                }

                cmdstr = cmdstr.Replace(";", "\r\n");
                frmHelp.txtProcessDrivercode(cmdstr, out txtbaseClearOriginal, out txtMClearOriginal);
                //MainForm.SendCmd(0);    //Write by Low Speed
                frmHelp.SendCmd(4);    //Write by High Speed
            }

            swVisionox.WriteLine("A9,00");
            swVisionox.WriteLine("60,01");
            swVisionox.Close();

            //select used group and disable CM function
            //REGISTER,A9,01,00;
            //REGISTER,60,01,00;
            cmdstr = "A9,00;60,00";

            cmdstr = cmdstr.Replace(";", "\r\n");
            frmHelp.txtProcessDrivercode(cmdstr, out txtbaseClearOriginal, out txtMClearOriginal);
            //MainForm.SendCmd(0);    //Write by Low Speed
            frmHelp.SendCmd(4);    //Write by High Speed

            switchPage(0);

            btnTuneCM.Enabled = true;
        }

        private void btnTuneOneClick_Click(object sender, EventArgs e)
        {
            btnTuneOneClick.Enabled = false;

            frmHelp.textBox1.Text += "Tune Nor 1\r\n";
            frmHelp.textBox1.SelectionStart = frmHelp.textBox1.TextLength;
            frmHelp.textBox1.ScrollToCaret();

            btnTuneGamma_Click(sender, e);

            if (StopTune)
            {
                btnTuneOneClick.Enabled = true;
                return;
            }

            frmHelp.textBox1.Text += "Tune IR\r\n";
            frmHelp.textBox1.SelectionStart = frmHelp.textBox1.TextLength;
            frmHelp.textBox1.ScrollToCaret();

            btnTuneIR_Click(sender, e);

            if (StopTune)
            {
                btnTuneOneClick.Enabled = true;
                return;
            }

            if (chkCmEn.Checked)
            {
                frmHelp.textBox1.Text += "Tune CGM\r\n";
                frmHelp.textBox1.SelectionStart = frmHelp.textBox1.TextLength;
                frmHelp.textBox1.ScrollToCaret();

                btnTuneCM_Click(sender, e);

                if (StopTune)
                {
                    btnTuneOneClick.Enabled = true;
                    return;
                }
            }

            frmHelp.textBox1.Text += "Tune Nor 2\r\n";
            frmHelp.textBox1.SelectionStart = frmHelp.textBox1.TextLength;
            frmHelp.textBox1.ScrollToCaret();

            btnTuneGammaN2_Click(sender, e);

            if (StopTune)
            {
                btnTuneOneClick.Enabled = true;
                return;
            }

            frmHelp.textBox1.Text += "Tune Nor 3\r\n";
            frmHelp.textBox1.SelectionStart = frmHelp.textBox1.TextLength;
            frmHelp.textBox1.ScrollToCaret();

            btnTuneGammaN3_Click(sender, e);

            if (StopTune)
            {
                btnTuneOneClick.Enabled = true;
                return;
            }

            frmHelp.textBox1.Text += "Tune AOD\r\n";
            frmHelp.textBox1.SelectionStart = frmHelp.textBox1.TextLength;
            frmHelp.textBox1.ScrollToCaret();

            btnTuneGammaAOD_Click(sender, e);

            btnTuneOneClick.Enabled = true;
        }

        private void btnStopTune_Click(object sender, EventArgs e)
        {
            StopTune = true;
        }
        private void btnTuneGamma_Click(object sender, EventArgs e)
        {
            string txtbaseClearOriginal;
            string txtMClearOriginal;

            // get value from tool interface
            int nHeight = int.Parse(txtResH.Text);
            int nWidth = int.Parse(txtResW.Text);
            int nNotchHeight = int.Parse(txtNotchH.Text);
            int blkImgSize = int.Parse(txtBlkImgSize.Text);

            float fNormTargetLv = float.Parse(txtNormDefLv.Text);
            float fNormTargetMinLv = float.Parse(txtNormDefMinLv.Text);
            float fNormTargetx = float.Parse(txtNormDefx.Text);
            float fNormTargety = float.Parse(txtNormDefy.Text);
            float fNormTolerance = float.Parse(txtNormTolerance.Text);
            float fTargetGamma = float.Parse(txtDefGamma.Text);

            int nTunePointNum = 24;
            int[] nTuneIndex = new int[24] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23 };

            int nVGMPAddrH, nVGMPAddrL, nVGSPAddrH, nVGSPAddrL;
            int[] nInitGamma = new int[3];
            int[] nSaveInitGamma = new int[3];
            float[] fMeasuredxyY = new float[3];
            float fx, fy, fLv;
            int nCurrGammaPoint, nPreGammaPoint;
            int loopCnt, nTestOK, i;
            int nPage;

            int[] nBlkBoxSize = new int[4];
            int[] nFullBoxSize = new int[4];

            tGammaParam = new DLLStructure.gammaParam_t();

            int nNorm;

            StopTune = false;
            btnTuneGamma.Enabled = false;

            //* * * * * * * * * *
            //* step 1 : get Normalize Point from IC or set by manual
            //* * * * * * * * * *
            nNorm = gnNormPoint;

            //* * * * * * * * * *
            //* step 2 : disable Demura, IR, CM function
            //* * * * * * * * * *
            disableIPFunc();

            //* * * * * * * * * *
            //* step 3 : get gamma bonding point from IC or set by manual
            //* * * * * * * * * *
            int nGammaPointNum = 24;
            tGammaParam.nGammaPointNum = nGammaPointNum;
            tGammaParam.anGammaPoint = new int[24] {0, 4, 12, 20, 28, 32, 36, 40, 44, 52, 84, 92, 112, 144, 176,
                                                  212, 340, 360, 616, 748, 812, 828, 956, 1020};

            tGammaParam.nCoefGammaNum = 5;
            tGammaParam.anCoefGamma = new int[5] { 4000, 3200, 2400, 1600, 1100 };

            tGammaParam.fxyYForRGB = new float[9];
            tGammaParam.coefxyY = new float[15];

            //* * * * * * * * * *
            //* step 4 : set coordinate of corner for tuning pattern
            //* * * * * * * * * *
            nBlkBoxSize[0] = (nWidth - blkImgSize) / 2;
            nBlkBoxSize[1] = (nHeight - blkImgSize) / 2;
            nBlkBoxSize[2] = (nWidth + blkImgSize) / 2;
            nBlkBoxSize[3] = (nHeight + blkImgSize) / 2;

            //set debug mode
            setDbgMode(1);

            //= = = = = = = = = = = = = = =
            // tune first normal gamma
            //= = = = = = = = = = = = = = =
            // set page number
            nPage = 0x09;
            // switch to prepare tuning gamma page
            //swtich to page 00
            //REGISTER,FF,3,78,38,00
            //Write 03,FF (2 byte) into address '51'
            cmdstr = "FF,78,38,00;51,03,FF";

            cmdstr = cmdstr.Replace(";", "\r\n");
            frmHelp.txtProcessDrivercode(cmdstr, out txtbaseClearOriginal, out txtMClearOriginal);
            //MainForm.SendCmd(0);    //Write by Low Speed
            frmHelp.SendCmd(4);    //Write by High Speed

            //* * * * * * * * * *
            //* step 5 : set target value : Lv, x, y, tolerance, gamma
            //* * * * * * * * * *
            tGammaParam.fTargetx = fNormTargetx;
            tGammaParam.fTargety = fNormTargety;
            tGammaParam.fTargetGamma = fTargetGamma;
            tGammaParam.fTolerance = fNormTolerance;
            tGammaParam.fTargetLv = fNormTargetLv;
            tGammaParam.nScale = nNorm;
            tGammaParam.nFixVGSP = 1;
            //* * * * * * * * * *
            //* step 6 : get VGMP / VGSP
            //* * * * * * * * * *
            nVGMPAddrH = 0x90 + (nPage - 0x09) * 4;
            nVGMPAddrL = 0x91 + (nPage - 0x09) * 4;
            nVGSPAddrH = 0x92 + (nPage - 0x09) * 4;
            nVGSPAddrL = 0x93 + (nPage - 0x09) * 4;
            if (txtNorm1VGMP.Text == "0" || txtNorm1VGSP.Text == "0")
            {
                tGammaParam.fVGMP = readVGP(nVGMPAddrH, nVGMPAddrL);
                tGammaParam.fVGSP = readVGP(nVGSPAddrH, nVGSPAddrL);
            }
            else
            {
                tGammaParam.fVGMP = float.Parse(txtNorm1VGMP.Text);
                tGammaParam.fVGSP = float.Parse(txtNorm1VGSP.Text);
            }

            //* * * * * * * * * *
            //* step 7 : show bist mode black pattern and measure its luminance
            //* * * * * * * * * *
            SetBlkPara(0, 0, 0, nBlkBoxSize[0], nBlkBoxSize[1], nBlkBoxSize[2], nBlkBoxSize[3]);
            StartBistMode();
            GetCAData(out fx, out fy, out fLv);
            tGammaParam.fBlackLv = fLv;

            //* * * * * * * * * *
            //* step 8 : show bist mode RGB 255 block pattern and measure their x, y, luminance
            //* * * * * * * * * *
            SetBlkPara(255, 0, 0, nBlkBoxSize[0], nBlkBoxSize[1], nBlkBoxSize[2], nBlkBoxSize[3]);
            GetCAData(out tGammaParam.fxyYForRGB[0], out tGammaParam.fxyYForRGB[1], out tGammaParam.fxyYForRGB[2]);

            SetBlkPara(0, 255, 0, nBlkBoxSize[0], nBlkBoxSize[1], nBlkBoxSize[2], nBlkBoxSize[3]);
            GetCAData(out tGammaParam.fxyYForRGB[3], out tGammaParam.fxyYForRGB[4], out tGammaParam.fxyYForRGB[5]);

            SetBlkPara(0, 0, 255, nBlkBoxSize[0], nBlkBoxSize[1], nBlkBoxSize[2], nBlkBoxSize[3]);
            GetCAData(out tGammaParam.fxyYForRGB[6], out tGammaParam.fxyYForRGB[7], out tGammaParam.fxyYForRGB[8]);

            //* * * * * * * * * *
            //* step 9 : show bist mode W 255 block pattern with different gamma index 
            //*          and measure their x, y, luminance
            //* * * * * * * * * *
            // Prestored gamma index of last one bonding point
            if (gnNormGammaIndex[0] == 0 || gnNormGammaIndex[1] == 0 || gnNormGammaIndex[2] == 0)
            {
                ReadGammaOfLastOnePoint(nPage, nInitGamma);
            }
            else
            {
                for (i = 0; i < 3; i++)
                {
                    nInitGamma[i] = gnNormGammaIndex[i];
                }
            }

            SetBlkPara(255, 255, 255, nBlkBoxSize[0], nBlkBoxSize[1], nBlkBoxSize[2], nBlkBoxSize[3]);
            for (i = 0; i < 5; i++)
            {
                WriteGammaOfLastOnePoint(nPage, tGammaParam.anCoefGamma[i], tGammaParam.anCoefGamma[i], tGammaParam.anCoefGamma[i]);
                GetCAData(out tGammaParam.coefxyY[i * 3 + 0], out tGammaParam.coefxyY[i * 3 + 1], out tGammaParam.coefxyY[i * 3 + 2]);
            }

            // restore gamma index  of last one bonding point
            WriteGammaOfLastOnePoint(nPage, nInitGamma[0], nInitGamma[1], nInitGamma[2]);

            //* * * * * * * * * *
            //* step 10 : set gamma parameter and calculate coefficient 
            //*           and return suitable VGSP to write into register
            //* * * * * * * * * *
            gammaSetParameter(ref tGammaParam);
            tGammaParam.fVGSP = genCoeficient();

            writeVGP(nVGSPAddrH, nVGSPAddrL, tGammaParam.fVGSP);

            txtNorm1VGSP.Text = tGammaParam.fVGSP.ToString();

            //* * * * * * * * * *
            //* step 11: tune gamma index for each gamma point from hight gray to low gray
            //* * * * * * * * * *
            // initial gamma index to 0
            for (i = 0; i < 72; i++)
            {
                nNewGammaIndexTable[i] = 0;
            }

            for (i = nTunePointNum - 1; i >= 0; i--)
            {
                frmHelp.textBox1.Text += "Tune Point " + (i + 1).ToString() + "\r\n";
                frmHelp.textBox1.SelectionStart = frmHelp.textBox1.TextLength;
                frmHelp.textBox1.ScrollToCaret();

                if (tGammaParam.anGammaPoint[nTuneIndex[i]] == 0)
                    continue;

                nCurrGammaPoint = tGammaParam.anGammaPoint[nTuneIndex[i]];

                if (i < (nTunePointNum - 1))
                {
                    nPreGammaPoint = tGammaParam.anGammaPoint[nTuneIndex[i + 1]];

                    // 提前計算下一個綁點的合適gamma index
                    preCalNodeGamma(nCurrGammaPoint, nPreGammaPoint, nInitGamma);
                    WriteGammaOfLastOnePoint(nPage, nInitGamma[0], nInitGamma[1], nInitGamma[2]);
                }

                float fTolerance = tGammaParam.fTolerance;
                float fTolerance_c = tGammaParam.fTolerance;
                loopCnt = 0;
                do
                {
                    GetCAData(out fMeasuredxyY[0], out fMeasuredxyY[1], out fMeasuredxyY[2]);

                    //根據輸入的光學資料,計算當前綁點合適的gamma index, 並將其寫入IC register
                    nTestOK = calNodeGamma(nCurrGammaPoint, fMeasuredxyY, fTolerance, fTolerance_c,
                                            nInitGamma, nSaveInitGamma);
                    WriteGammaOfLastOnePoint(nPage, nInitGamma[0], nInitGamma[1], nInitGamma[2]);

                    loopCnt++;

                    if (StopTune)
                    {
                        StopBistMode();
                        frmHelp.GrayShow(0, 0, 0);
                        btnTuneGamma.Enabled = true;
                        return;
                    }
                } while (nTestOK == 0 && loopCnt < 9);

                //若Tune了9次還逹不到Tolerance要求,則改用誤差最小的那一組gamma index
                if (nTestOK == 0 && loopCnt >= 9)
                {
                    nInitGamma[0] = nSaveInitGamma[0];
                    nInitGamma[1] = nSaveInitGamma[1];
                    nInitGamma[2] = nSaveInitGamma[2];
                }

                // 暫存每一組Tune好的綁點gamma index
                nNewGammaIndexTable[nTuneIndex[i]] = nInitGamma[0];
                nNewGammaIndexTable[nTuneIndex[i] + nGammaPointNum] = nInitGamma[1];
                nNewGammaIndexTable[nTuneIndex[i] + nGammaPointNum * 2] = nInitGamma[2];
            }

            StopBistMode();
            frmHelp.GrayShow(0, 0, 0);

            //* * * * * * * * * *
            // step 12 : 若未Tune滿24個綁點gamma index, 其餘綁點的gamma index使用內插計算方式
            //* * * * * * * * * *
            InterpolateGamma(nNewGammaIndexTable, nTuneIndex, nTunePointNum);

            //* * * * * * * * * *
            // step 13: 將24個綁點的gamma index寫入相對應的register內
            //* * * * * * * * * *
            WriteAllGamma(nPage, nNewGammaIndexTable);

            //* * * * * * * * * *
            // step 14: 將24個綁點的gamma index輸出到外部檔案
            //* * * * * * * * * *
            int Addr = 0;
            int nVGMPIdx = (int)(((tGammaParam.fVGMP - 0.4) / 0.01) + 0.5f) + 0x10;
            int nVGSPIdx = (int)(((tGammaParam.fVGSP - 0.4) / 0.01) + 0.5f) + 0x10;

            string strData;
            string strVisionox = System.Windows.Forms.Application.StartupPath + "/ILI8818_gamma_page" + nPage.ToString("X2") + "_" + (tGammaParam.fTargetLv).ToString() + "nits_visionox.txt";
            string strILI = System.Windows.Forms.Application.StartupPath + "/ILI8818_gamma_page" + nPage.ToString("X2") + "_" + (tGammaParam.fTargetLv).ToString() + "nits_ili.txt";
            StreamWriter swVisionox = new StreamWriter(strVisionox);
            StreamWriter swILI = new StreamWriter(strILI);

            //Visionox format
            NumericUpDown[] NUMR = new NumericUpDown[] { num_ILI8818_R0, num_ILI8818_R1, num_ILI8818_R2, num_ILI8818_R3, num_ILI8818_R4, num_ILI8818_R5, num_ILI8818_R6, num_ILI8818_R7, num_ILI8818_R8, num_ILI8818_R9, num_ILI8818_R10, num_ILI8818_R11, num_ILI8818_R12, num_ILI8818_R13, num_ILI8818_R14, num_ILI8818_R15, num_ILI8818_R16, num_ILI8818_R17, num_ILI8818_R18, num_ILI8818_R19, num_ILI8818_R20, num_ILI8818_R21, num_ILI8818_R22, num_ILI8818_R23 };
            NumericUpDown[] NUMG = new NumericUpDown[] { num_ILI8818_G0, num_ILI8818_G1, num_ILI8818_G2, num_ILI8818_G3, num_ILI8818_G4, num_ILI8818_G5, num_ILI8818_G6, num_ILI8818_G7, num_ILI8818_G8, num_ILI8818_G9, num_ILI8818_G10, num_ILI8818_G11, num_ILI8818_G12, num_ILI8818_G13, num_ILI8818_G14, num_ILI8818_G15, num_ILI8818_G16, num_ILI8818_G17, num_ILI8818_G18, num_ILI8818_G19, num_ILI8818_G20, num_ILI8818_G21, num_ILI8818_G22, num_ILI8818_G23 };
            NumericUpDown[] NUMB = new NumericUpDown[] { num_ILI8818_B0, num_ILI8818_B1, num_ILI8818_B2, num_ILI8818_B3, num_ILI8818_B4, num_ILI8818_B5, num_ILI8818_B6, num_ILI8818_B7, num_ILI8818_B8, num_ILI8818_B9, num_ILI8818_B10, num_ILI8818_B11, num_ILI8818_B12, num_ILI8818_B13, num_ILI8818_B14, num_ILI8818_B15, num_ILI8818_B16, num_ILI8818_B17, num_ILI8818_B18, num_ILI8818_B19, num_ILI8818_B20, num_ILI8818_B21, num_ILI8818_B22, num_ILI8818_B23 };

            strData = "FF,78,38," + nPage.ToString("X2");
            swVisionox.WriteLine(strData);
            Addr = 0;
            for (i = 0; i < 72; i++)
            {
                strData = Addr.ToString("X2") + "," + ((nNewGammaIndexTable[i] & 0x0000FF00) >> 8).ToString("X2");
                swVisionox.WriteLine(strData);
                Addr++;

                strData = Addr.ToString("X2") + "," + ((nNewGammaIndexTable[i] & 0x000000FF)).ToString("X2");
                swVisionox.WriteLine(strData);
                Addr++;
            }
            for (i = 0; i < 24; i++)
            {
                //    strData = "R" + i.ToString() + "," + nNewGammaIndexTable[i].ToString("X4") + ",G" + i.ToString() + "," + nNewGammaIndexTable[24 + i].ToString("X4") + ",B" + i.ToString() + "," + nNewGammaIndexTable[48 + i].ToString("X4");
                //    swVisionox.WriteLine(strData);

                NUMR[i].Value = nNewGammaIndexTable[i];
                NUMG[i].Value = nNewGammaIndexTable[i + 24];
                NUMB[i].Value = nNewGammaIndexTable[i + 48];
            }
            swVisionox.WriteLine("FF,78,38,0C");
            strData = nVGMPAddrH.ToString("X2") + "," + ((nVGMPIdx & 0x0000FF00) >> 8).ToString("X2");
            swVisionox.WriteLine(strData);
            strData = nVGMPAddrL.ToString("X2") + "," + ((nVGMPIdx & 0x000000FF)).ToString("X2");
            swVisionox.WriteLine(strData);
            strData = nVGSPAddrH.ToString("X2") + "," + ((nVGSPIdx & 0x0000FF00) >> 8).ToString("X2");
            swVisionox.WriteLine(strData);
            strData = nVGSPAddrL.ToString("X2") + "," + ((nVGSPIdx & 0x000000FF)).ToString("X2");
            swVisionox.WriteLine(strData);

            // ILITek format
            strData = "REGISTER,FF,3,78,38," + nPage.ToString("X2");
            swILI.WriteLine(strData);
            Addr = 0;
            for (i = 0; i < 72; i++)
            {
                strData = "REGISTER," + Addr.ToString("X2") + ",1," + ((nNewGammaIndexTable[i] & 0x0000FF00) >> 8).ToString("X2");
                swILI.WriteLine(strData);
                Addr++;

                strData = "REGISTER," + Addr.ToString("X2") + ",1," + ((nNewGammaIndexTable[i] & 0x000000FF)).ToString("X2");
                swILI.WriteLine(strData);
                Addr++;
            }
            swILI.WriteLine("\nREGISTER,FF,03,78,38,0C");

            strData = "REGISTER," + nVGMPAddrH.ToString("X2") + ",01," + ((nVGMPIdx & 0x0000FF00) >> 8).ToString("X2");
            swILI.WriteLine(strData);
            strData = "REGISTER," + nVGMPAddrL.ToString("X2") + ",01," + ((nVGMPIdx & 0x000000FF)).ToString("X2");
            swILI.WriteLine(strData);
            strData = "REGISTER," + nVGSPAddrH.ToString("X2") + ",01," + ((nVGSPIdx & 0x0000FF00) >> 8).ToString("X2");
            swILI.WriteLine(strData);
            strData = "REGISTER," + nVGSPAddrL.ToString("X2") + ",01," + ((nVGSPIdx & 0x000000FF)).ToString("X2");
            swILI.WriteLine(strData);

            swVisionox.Close();
            swILI.Close();

            frmHelp.textBox1.Text += "Tune Done\r\n";
            frmHelp.textBox1.SelectionStart = frmHelp.textBox1.TextLength;
            frmHelp.textBox1.ScrollToCaret();

            btnTuneGamma.Enabled = true;
        }

        private void Demura_Click_Simplify(object sender, EventArgs e)
        {
            Button btnTmp = (Button)sender;
            Send_buf = new byte[10];
            Setting.TempRecord.cmdLen = 10;
            Send_buf[0] = 0x2F;
            Send_buf[2] = 0x05;
            Send_buf[3] = 0x29;
            switch (btnTmp.Name)
            {
                case "btn_DeMura_EN":
                    {
                        Send_buf[1] = 0x01; //0x06
                    }
                    break;

                case "btn_DeMura_Erase":
                    {
                        Send_buf[1] = 0x05;
                    }
                    break;

                case "btn_DeMura_Into":
                    {
                        //Send_buf[1] = 0x01;
                        PreLoad_Demura_data_Click();
                    }
                    break;

                case "btn_DeMura_Enter":
                    {
                        Send_buf[1] = 0x04;
                    }
                    break;

                case "btn_DeMura_Wrting":
                    {
                        Send_buf[1] = 0x06;
                        MessageBox.Show("烧录数据大约需要5s，等待返回De-Mura Data Writing Successful.信息");
                    }
                    break;

                case "btn_DeMura_Reload_Data":
                    {

                        Send_buf[1] = 0x07;
                    }
                    break;
                case "btn_DeMura_Function_On":
                    {
                        Send_buf[1] = 0x09;
                    }
                    break;

                case "btn_DeMura_Function_Off":
                    {
                        Send_buf[1] = 0x0A;
                    }
                    break;
                default:
                    frmHelp.textBox1.Text = "DeMura 按键异常！！";
                    break;
            }
            CRCData.CalculateCrc16(Send_buf, out Send_buf[8], out Send_buf[9]);
            try
            {
                frmHelp.comPort.Write(Send_buf, 0, 10);
            }
            catch
            {
                MessageBox.Show("串口有误，请检查", "错误");
                return;
            }
        }

        private void PreLoad_Demura_data_Click()  //预加载Demura文件
        {
            Int32 m_txlen = 0;
            Int32 Once_txlen = 0;
            Int32 File_Length, File_Length_tep;
            bool tx_en = true;
            byte[] TemFileContent = new byte[1024 * 100];
            char[] Acsii_array = new char[2];
            Int32 div = 0;

            div = Convert.ToInt16(frmHelp.HACT.Value) * 3;
            System.Int32 ByteReaded = 0x00;
            try
            {
                OpenFileDialog of = new OpenFileDialog();
                of.Filter = "文本文件(*.txt)|*.txt|所有文件(*.*)|*.*";
                of.Title = "初始化 Code";
                string str = "";
                if (of.ShowDialog() == DialogResult.OK)
                {
                    StreamReader streamReader = new StreamReader(of.FileName, Encoding.Default);
                    str = streamReader.ReadToEnd();
                    streamReader.Close();
                    str = str.Replace("\r\n", " ");//测试档用的是\r\n


                }


                string[] arr = str.Trim().Split(' '); //字符串拆分成数组
                //Int32 x = Convert.ToInt32(arr2.Length * 1.5);
                //string[] arr = new string[x];
                //Int32 m = 0;
                //for (int i = 0; i < arr2.Length * 1.5; i++)
                //{

                //    if (i % 3 == 0)
                //    {
                //        arr[i] = arr2[m + 1];
                //        //m++;
                //    }
                //    else if (i % 3 == 1)
                //    {
                //        arr[i] = arr2[m];
                //        m++; m++;
                //    }
                //    else //(i % 3 == 2)
                //        arr[i] = "0";
                //}

                File_Length = Convert.ToInt32(arr.Length);
                File_Length_tep = File_Length;

                //00000000000000000000000000000000000000
                frmHelp.textBox1.Text += "设定 Demura Flag \r\n";
                try
                { //Demura 告诉下位机Demura数据搬运开始
                    TemFileContent[1] = 0x1F;
                    TemFileContent[2] = 0xbd;
                    TemFileContent[3] = 0xcf;
                    TemFileContent[4] = 0xfc;
                    TemFileContent[5] = 0xac;
                    TemFileContent[6] = 0xca;
                    TemFileContent[7] = Convert.ToByte(File_Length >> 24);
                    TemFileContent[8] = Convert.ToByte((File_Length >> 16) & 0xff);
                    TemFileContent[9] = Convert.ToByte((File_Length >> 8) & 0xff);
                    TemFileContent[10] = Convert.ToByte(File_Length & 0xff);
                    frmHelp.comPort.Write(TemFileContent, 0, 11);
                }
                catch
                {
                    MessageBox.Show("串口有误，请检查", "错误");
                    tx_en = false;
                    return;
                }
                //00000000000000000000000000000000000000


                while (tx_en)
                {
                    if (File_Length_tep > (File_Length % div))
                    {
                        Once_txlen = div;
                    }
                    else  //最后一笔
                    {
                        Once_txlen = Convert.ToInt32(arr.Length % div);
                        tx_en = false;
                    }
                    //aFile.Seek(0 + m_txlen, SeekOrigin.Begin);    //跳转
                    ByteReaded = Once_txlen; // 存入第0位
                    for (int i = 0; i < Once_txlen; i++)
                    {
                        TemFileContent[i + 0] = byte.Parse((Convert.ToInt32(arr[i + m_txlen], 16)).ToString());
                    }
                    try
                    {
                        frmHelp.comPort.Write(TemFileContent, 0, ByteReaded + 0);
                    }
                    catch
                    {
                        MessageBox.Show("串口有误，请检查", "错误");
                        tx_en = false;
                        break;
                    }
                    //tx_en = false;
                    m_txlen += ByteReaded;
                    progressBar2.Value = Convert.ToInt32((double)m_txlen / File_Length * 100);
                    label_flash.Text = progressBar2.Value.ToString() + "%";
                    Application.DoEvents();//重点，必须加上，否则父子窗体都假死
                    File_Length_tep = File_Length_tep - div;
                }
                //aFile.Close();
            }
            catch
            {
                MessageBox.Show("请选择文件夹", "错误");
            }
        }
        #endregion



        private void ILI8818_OTP_Click(object sender, EventArgs e)
        {
            Send_buf = new byte[8];
            Setting.TempRecord.cmdLen = 8;
            Send_buf[0] = 0x6F;
            Send_buf[1] = 0x07;
            Send_buf[2] = 3;
            CRCData.CalculateCrc16(Send_buf, out Send_buf[Setting.TempRecord.cmdLen - 2], out Send_buf[Setting.TempRecord.cmdLen - 1]);
            try
            {
                frmHelp.comPort.Write(Send_buf, 0, Setting.TempRecord.cmdLen);   //
            }
            catch
            {
                MessageBox.Show("串口有误，请检查", "错误");
            }
        }

        private void ChkCMD3_CheckedChanged(object sender, EventArgs e)
        {

        }

        private void T1_Tick(object sender, EventArgs e)
        {
            txttip.Text += "已完成。。。。。。。。。。.\r\n";

            txttip.Select(txttip.Text.Length, 0);
            txttip.ScrollToCaret();
            T1.Enabled = false;
        }

        private void btn_DeMura_Load_Data_Click(object sender, EventArgs e)
        {
            txt_Reg_Data_WR.Text = "FF,78,38,00";
            ILI8818_Others_Click(btn_Reg_W, e);
            Thread.Sleep(10);
            PreLoad_Demura_data_Click();
        }
        private void button2_Click(object sender, EventArgs e)
        {
            txt_Reg_Data_WR.Text = "FF,78,38,0C";
            ILI8818_Others_Click(btn_Reg_W, e);
            txt_Reg_Data_WR.Text = "E3,01";  //解锁
            ILI8818_Others_Click(btn_Reg_W, e);
            if (rbt_ILI8818_Normal_1.Checked == true) { txt_Reg_Data_WR.Text = "FF,78,38,20"; }
            //else if (rbt_ILI8818_Normal_2.Checked == true) {  txt_Reg_Data_WR.Text = "FF,78,38,0A"; }
            //else if (rbt_ILI8818_Normal_3.Checked == true) {  txt_Reg_Data_WR.Text = "FF,78,38,0B"; }
            //else if (rbt_ILI8818_Normal_4.Checked == true) {  txt_Reg_Data_WR.Text = "FF,78,38,0C"; }
            else if (rbt_ILI8818_HBM.Checked == true) { txt_Reg_Data_WR.Text = "FF,78,38,1E"; }//E
            else if (rbt_ILI8818_AOD.Checked == true) { txt_Reg_Data_WR.Text = "FF,78,38,2B"; }//F
            Thread.Sleep(100); //毫秒
            ILI8818_Others_Click(btn_Reg_W, e);
            frmHelp.auto_gamma_write(3, 0X11, 3, 0X22, 3, 0X33);
        }

        #region //通用命令处理
        private void PAGE_comboBox_FontChanged(object sender, EventArgs e)
        {
            switch (PAGE_comboBox.SelectedIndex)
            {
                case 0://0、60hz FFFH  800nit page36/34
                    {
                        txtCmd6.Text = "FF,78,38,00\r\n51,0F,FF// 进HBM\r\nFF,78,38,02\r\n38,33// 60HZ\r\nFF,78,38,0C\r\nE3,01 // 解锁\r\nFF,78,38,36//PAGE &调完写page34";
                        txtCmd7.Text = "FF,78,38,36//PAGE";
                    }
                    break;
                case 1://1、60hz DBBH 500nit page37
                    {
                        txtCmd6.Text = "FF,78,38,00\r\n51,0D,BB// 进HBM\r\nFF,78,38,02\r\n38,33// 60HZ\r\nFF,78,38,0C\r\nE3,01 // 解锁\r\nFF,78,38,37//PAGE ";
                        txtCmd7.Text = "FF,78,38,37//PAGE";
                    }
                    break;
                case 3://3、60hz 503H  50nit   page39
                    {
                        txtCmd6.Text = "FF,78,38,00\r\n51,05,03// 进HBM\r\nFF,78,38,02\r\n38,33// 60HZ\r\nFF,78,38,0C\r\nE3,01 // 解锁\r\nFF,78,38,39//PAGE ";
                        txtCmd7.Text = "FF,78,38,39//PAGE";
                    }
                    break;
                case 4://4、60hz 2DBH  2nit    page3A
                    {
                        txtCmd6.Text = "FF,78,38,00\r\n51,02,DB// 进HBM\r\nFF,78,38,02\r\n38,33// 60HZ\r\nFF,78,38,0C\r\nE3,01 // 解锁\r\nFF,78,38,3A//PAGE ";
                        txtCmd7.Text = "FF,78,38,3A//PAGE";
                    }
                    break;
                case 5://5、60hz 16CH  200nit page3B
                    {
                        txtCmd6.Text = "FF,78,38,00\r\n51,01,6C// 进HBM\r\nFF,78,38,02\r\n38,33// 60HZ\r\nFF,78,38,0C\r\nE3,01 // 解锁\r\nFF,78,38,3B//PAGE ";
                        txtCmd7.Text = "FF,78,38,3B//PAGE";
                    }
                    break;
                case 6://6、60hz  DAH  50nit   page3C
                    {
                        txtCmd6.Text = "FF,78,38,00\r\n51,00,DA// 进HBM\r\nFF,78,38,02\r\n38,33// 60HZ\r\nFF,78,38,0C\r\nE3,01 // 解锁\r\nFF,78,38,3C//PAGE ";
                        txtCmd7.Text = "FF,78,38,3C//PAGE";
                    }
                    break;
                case 7://7、60hz  1H     2nit     page3D
                    {
                        txtCmd6.Text = "FF,78,38,00\r\n51,00,01// 进HBM\r\nFF,78,38,02\r\n38,33// 60HZ\r\nFF,78,38,0C\r\nE3,01 // 解锁\r\nFF,78,38,3D//PAGE ";
                        txtCmd7.Text = "FF,78,38,3D//PAGE";
                    }
                    break;
                case 8://8、90hz FFFH  800nit page2B/29
                    {
                        txtCmd6.Text = "FF,78,38,00\r\n51,0F,FF// 进HBM\r\nFF,78,38,02\r\n38,32// 90HZ\r\nFF,78,38,0C\r\nE3,01 // 解锁\r\nFF,78,38,2B//PAGE &调完写page29";
                        txtCmd7.Text = "FF,78,38,2B//PAGE";
                    }
                    break;
                case 9://9、90hz DBBH 500nit page2C
                    {
                        txtCmd6.Text = "FF,78,38,00\r\n51,0D,BB// 进HBM\r\nFF,78,38,02\r\n38,32// 90HZ\r\nFF,78,38,0C\r\nE3,01 // 解锁\r\nFF,78,38,2C//PAGE";
                        txtCmd7.Text = "FF,78,38,2C//PAGE";
                    }
                    break;
                case 10://10、90hz 985H  200nit page2D
                    {
                        txtCmd6.Text = "FF,78,38,00\r\n51,09,85// 进HBM\r\nFF,78,38,02\r\n38,32// 90HZ\r\nFF,78,38,0C\r\nE3,01 // 解锁\r\nFF,78,38,2D//PAGE";
                        txtCmd7.Text = "FF,78,38,2D//PAGE";
                    }
                    break;
                case 11://11、90hz 503H  50nit   page2E
                    {
                        txtCmd6.Text = "FF,78,38,00\r\n51,05,03// 进HBM\r\nFF,78,38,02\r\n38,32// 90HZ\r\nFF,78,38,0C\r\nE3,01 // 解锁\r\nFF,78,38,2E//PAGE";
                        txtCmd7.Text = "FF,78,38,2E//PAGE";
                    }
                    break;
                case 12://12、90hz 2DBH  2nit    page2F
                    {
                        txtCmd6.Text = "FF,78,38,00\r\n51,02,DB// 进HBM\r\nFF,78,38,02\r\n38,32// 90HZ\r\nFF,78,38,0C\r\nE3,01 // 解锁\r\nFF,78,38,2F//PAGE";
                        txtCmd7.Text = "FF,78,38,2F//PAGE";
                    }
                    break;
                case 13://13、90hz 16CH  200nit page30
                    {
                        txtCmd6.Text = "FF,78,38,00\r\n51,01,6C// 进HBM\r\nFF,78,38,02\r\n38,32// 90HZ\r\nFF,78,38,0C\r\nE3,01 // 解锁\r\nFF,78,38,30//PAGE";
                        txtCmd7.Text = "FF,78,38,30//PAGE";
                    }
                    break;
                case 14://14、90hz  DAH  50nit   page31
                    {
                        txtCmd6.Text = "FF,78,38,00\r\n51,00,DA// 进HBM\r\nFF,78,38,02\r\n38,32// 90HZ\r\nFF,78,38,0C\r\nE3,01 // 解锁\r\nFF,78,38,31//PAGE";
                        txtCmd7.Text = "FF,78,38,31//PAGE";
                    }
                    break;
                case 15://15、90hz  1H     2nit     page32
                    {
                        txtCmd6.Text = "FF,78,38,00\r\n51,00,01// 进HBM\r\nFF,78,38,02\r\n38,32// 90HZ\r\nFF,78,38,0C\r\nE3,01 // 解锁\r\nFF,78,38,32//PAGE";
                        txtCmd7.Text = "FF,78,38,32//PAGE";
                    }
                    break;
                case 16://16、120hz FFFH  800nit page20/1E
                    {
                        txtCmd6.Text = "FF,78,38,00\r\n51,0F,FF// 进HBM\r\nFF,78,38,02\r\n38,31// 90HZ\r\nFF,78,38,0C\r\nE3,01 // 解锁\r\nFF,78,38,20//PAGE &调完写page1E";
                        txtCmd7.Text = "FF,78,38,20//PAGE";
                    }
                    break;
                case 17://17、120hz DBBH 500nit page21
                    {
                        txtCmd6.Text = "FF,78,38,00\r\n51,0D,BB// 进HBM\r\nFF,78,38,02\r\n38,31// 90HZ\r\nFF,78,38,0C\r\nE3,01 // 解锁\r\nFF,78,38,21//PAGE";
                        txtCmd7.Text = "FF,78,38,21//PAGE";
                    }
                    break;
                case 18://18、120hz 985H  200nit page22
                    {
                        txtCmd6.Text = "FF,78,38,00\r\n51,09,85// 进HBM\r\nFF,78,38,02\r\n38,31// 90HZ\r\nFF,78,38,0C\r\nE3,01 // 解锁\r\nFF,78,38,22//PAGE";
                        txtCmd7.Text = "FF,78,38,22//PAGE";
                    }
                    break;
                case 19://19、120hz 503H  50nit   page23
                    {
                        txtCmd6.Text = "FF,78,38,00\r\n51,05,03// 进HBM\r\nFF,78,38,02\r\n38,31// 90HZ\r\nFF,78,38,0C\r\nE3,01 // 解锁\r\nFF,78,38,23//PAGE";
                        txtCmd7.Text = "FF,78,38,23//PAGE";
                    }
                    break;
                case 20://20、120hz 2DBH  2nit    page24
                    {
                        txtCmd6.Text = "FF,78,38,00\r\n51,02,DB// 进HBM\r\nFF,78,38,02\r\n38,31// 90HZ\r\nFF,78,38,0C\r\nE3,01 // 解锁\r\nFF,78,38,24//PAGE";
                        txtCmd7.Text = "FF,78,38,24//PAGE";
                    }
                    break;
                case 21://21、120hz 16CH  200nit page25
                    {
                        txtCmd6.Text = "FF,78,38,00\r\n51,01,6C// 进HBM\r\nFF,78,38,02\r\n38,31// 90HZ\r\nFF,78,38,0C\r\nE3,01 // 解锁\r\nFF,78,38,25//PAGE";
                        txtCmd7.Text = "FF,78,38,25//PAGE";
                    }
                    break;
                case 22://22、120hz  DAH  50nit   page26
                    {
                        txtCmd6.Text = "FF,78,38,00\r\n51,00,DA// 进HBM\r\nFF,78,38,02\r\n38,31// 90HZ\r\nFF,78,38,0C\r\nE3,01 // 解锁\r\nFF,78,38,26//PAGE";
                        txtCmd7.Text = "FF,78,38,26//PAGE";
                    }
                    break;
                case 23://23、120hz  1H     2nit     page27
                    {
                        txtCmd6.Text = "FF,78,38,00\r\n51,00,01// 进HBM\r\nFF,78,38,02\r\n38,31// 90HZ\r\nFF,78,38,0C\r\nE3,01 // 解锁\r\nFF,78,38,27//PAGE";
                        txtCmd7.Text = "FF,78,38,27//PAGE";
                    }
                    break;
                default: break;
            }
        }
        private void Send_Cmd_Click(object sender, EventArgs e)
        {
            Button btn = (Button)sender;
            switch (btn.Name)
            {
                case "btnSend1":
                    {
                        frmHelp.txtProcessDrivercode(txtCmd1.Text, out string txtbaseClearOriginal, out string txtMCleatOriginal);
                        MessageBox.Show("请等待20S!!!");
                        T1.Interval = 20000;
                        T1.Enabled = true;
                    }
                    break;
                case "btnSend2":
                    {
                        frmHelp.txtProcessDrivercode(txtCmd2.Text, out string txtbaseClearOriginal, out string txtMCleatOriginal);
                        MessageBox.Show("请按照624x1344送图!!!");
                    }
                    break;
                case "btnSend3":
                    {
                        frmHelp.txtProcessDrivercode(txtCmd3.Text, out string txtbaseClearOriginal, out string txtMCleatOriginal);
                        MessageBox.Show("等待3S后完成烧录，更换点code!");
                        T1.Interval = 4000;
                        T1.Enabled = true;
                    }
                    break;
                case "btnSend4":
                    {
                        frmHelp.txtProcessDrivercode(txtCmd4.Text, out string txtbaseClearOriginal, out string txtMCleatOriginal);
                    }
                    break;
                case "btnSend5":
                    {
                        frmHelp.txtProcessDrivercode(txtCmd5.Text, out string txtbaseClearOriginal, out string txtMCleatOriginal);
                    }
                    break;
                case "btnSend6_W":
                    {
                        frmHelp.txtProcessDrivercode(txtCmd6.Text, out string txtbaseClearOriginal, out string txtMCleatOriginal);
                    }
                    break;
                case "btnSend7_R":
                    {
                        frmHelp.txtProcessDrivercode(txtCmd7.Text, out string txtbaseClearOriginal, out string txtMCleatOriginal);
                    }
                    break;
                case "btnSend8":
                    {
                        frmHelp.txtProcessDrivercode(txtCmd8.Text, out string txtbaseClearOriginal, out string txtMCleatOriginal);
                    }
                    break;
                case "btnSend9":
                    {
                        frmHelp.txtProcessDrivercode(txtCmd9.Text, out string txtbaseClearOriginal, out string txtMCleatOriginal);
                    }
                    break;

            }
            Setting.TempRecord.cmdLen = 6;
            if (rBt_LP_DCS_Long_Write.Checked | rBt_LP_DCS_Short_Write.Checked | rBt_LP_Gerneric_Long_Write.Checked | rBt_LP_Gerneric_Short_Write.Checked)
            {
                frmHelp.SendCmd(0);
            }
            else
            {
                frmHelp.SendCmd(4);
            }
            txttip.Text += "命令已下发...\r\n";
            txttip.Select(txttip.Text.Length, 0);
            txttip.ScrollToCaret();
        }
        private void SaveCode_Click(object sender, EventArgs e)
        {
            SaveFileDialog txt = new SaveFileDialog();
            txt.Filter = @"txt文件(*.txt)|*.txt|所有文件(*.*)|*.*";
            string str = "//-----保存Driver IC Code文件------\r\n";
            if (txt.ShowDialog() == DialogResult.OK)
            {
                if (txt.FileName == " ")
                {
                    return;
                }
                StreamWriter sw = null; //文件流
                sw = new StreamWriter(txt.FileName, false, Encoding.GetEncoding("UTF-8"));//Encoding.GetEncoding("UTF-8")
                try
                {
                    if (ChkCMD1.Checked)
                    {
                        str += "//---CMD1---\r\n" + txtCmd1.Text;// lstMIPIDriver.Items[i].ToString();
                        str += "\r\n\r\n";
                    }
                    if (ChkCMD2.Checked)
                    {
                        str += "//---CMD2---\r\n" + txtCmd2.Text;// lstMIPIDriver.Items[i].ToString();
                        str += "\r\n\r\n";
                    }
                    if (ChkCMD3.Checked)
                    {
                        str += "//---CMD3---\r\n" + txtCmd3.Text;// lstMIPIDriver.Items[i].ToString();
                        str += "\r\n\r\n";
                    }
                    sw.Write(str);
                    sw.Dispose(); //释放资源
                    sw.Close(); //关闭数据流
                    MessageBox.Show("Driver IC Code保存OK！", "系统提示：");
                }
                catch
                {
                    MessageBox.Show("Driver IC Code保存时发生错误，请再试！", "系统提示：");
                }
            }
        }

        private void IC_comboBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            switch (IC_comboBox.SelectedIndex)
            {
                case 0://644+8818
                    {
                        txtCmd1.Text = "//1.RAM_TO_FLASH_FLOW_A（擦除）\r\nFF,78,38,08\r\nB2,21\r\n99,00\r\n9A,00\r\n9B,00\r\n9C,29\r\n9D,F1\r\n9E,8F\r\nA5,29\r\nA6,F2\r\nA7,00\r\nA8,33\r\nA9,E9\r\nAA,7F\r\nFF,78,38,0A\r\n" +
                            "30,00\r\nFF,78,38,00\r\n28\r\n11\r\nFF,FF,FF,AA\r\nFF,78,38,08\r\n93,00\r\n8F,06\r\nFF,FF,FF,10\r\n93,C0\r\nFF,FF,FF,10\r\n93,00\r\n8F,C7\r\nFF,FF,FF,1\r\n93,C0\r\n";
                        txtCmd2.Text = "//2.RAM_TO_FLASH_FLOW_A（擦除）\r\nFF,78,38,19\r\nE0,18\r\nDF,55\r\nEE,10\r\nFF,FF,FF,1\r\nFF,78,38,00\r\n3A,07\r\n";

                    }
                    break;
                case 1://7835+672单刷新率
                    {
                        txtCmd1.Text = "//1.RAM_TO_FLASH_FLOW_A（擦除）\r\nFF,78,38,06\r\n94,C0\r\nFF, FF, FF,10\r\nFF,78,38,08\r\nB2,21\r\n99,00\r\n9A,00\r\n9B,00\r\n9C,1F\r\n9D,EA\r\n9E,DF\r\n9F,00\r\n" +
"A0,00\r\nA1,00\r\nA2,00\r\nA3,00\r\nA4,00\r\nA5,29\r\nA6,F1\r\nA7,90\r\nA8,33\r\nA9,E9\r\nAA,0F\r\nFF,78,38,0A\r\n29,00\r\n2A,00\r\n2B,00\r\n2C,00\r\n2D,00\r\n2E,00\r\n30,0F\r\nFF,78,38,0A\r\n" +
                            "30,00\r\nFF,78,38,00\r\n28\r\n11\r\nFF,FF,FF,AA\r\nFF,78,38,08\r\n93,00\r\n8F,06\r\nFF,FF,FF,10\r\n93,C0\r\nFF,FF,FF,10\r\n93,00\r\n8F,C7\r\nFF,FF,FF,1\r\n93,C0\r\n";
                        txtCmd2.Text = "//2.RAM_TO_FLASH_FLOW_A（擦除）\r\nFF,78,38,19\r\nE0,18\r\nDF,55\r\nEE,10\r\nFF,FF,FF,1\r\nFF,78,38,00\r\n3A,07\r\n";
                    }
                    break;
                case 2://2 7838+672双套第一套M1
                    {
                        txtCmd1.Text = "//1.RAM_TO_FLASH_FLOW_A（擦除）\r\nFF,78,38,06\r\n94,C0\r\nFF,FF,FF,10\r\n" +
                            "FF,78,38,08\r\nB2,23\r\n99,00\r\n9A,00\r\n9B,00\r\n9C,0F\r\n9D,F5\r\n9E,6F\r\n9F,0F\r\nA0,F5\r\nA1,70\r\nA2,1F\r\nA3,EA\r\nA4,DF\r\n" +
                            "A5,29\r\nA6,F1\r\nA7,90\r\nA8,33\r\nA9,E9\r\nAA,0F\r\nFF,78,38,0A\r\n29,71\r\n2A,7C\r\n2B,00\r\n2C,00\r\n2D,00\r\n2E,00\r\n30,0F\r\n" +
"FF,78,38,0A\r\n30,00\r\nFF,78,38,00\r\n28\r\n11\r\nFF,FF,FF,AA\r\nFF,78,38,08\r\n93,00\r\n8F,06\r\nFF,FF,FF,10\r\n93,C0\r\nFF,FF,FF,10\r\n93,00\r\n8F,C7\r\nFF,FF,FF,1\r\n93,C0\r\n";
                        txtCmd2.Text = "//2.RAM_TO_FLASH_FLOW_A（擦除）\r\nFF,78,38,19\r\nE0,18\r\nDF,55\r\nEE,10\r\nFF,FF,FF,1\r\nFF,78,38,00\r\n3A,07\r\n";
                    }
                    break;
                case 3://2 7838+672双套第一套M2
                    {
                        txtCmd1.Text = "//1.RAM_TO_FLASH_FLOW_A（擦除）\r\nFF,78,38,06\r\n94,C0\r\nFF,FF,FF,10\r\n" +
                            "FF,78,38,08\r\nB2,23\r\n99,00\r\n9A,00\r\n9B,00\r\n9C,0F\r\n9D,F5\r\n9E,6F\r\n9F,0F\r\nA0,F5\r\nA1,70\r\nA2,1F\r\nA3,EA\r\nA4,DF\r\n" +
                            "A5,29\r\nA6,F1\r\nA7,90\r\nA8,33\r\nA9,E9\r\nAA,0F\r\nFF,78,38,0A\r\n29,71\r\n2A,7C\r\n2B,00\r\n2C,00\r\n2D,00\r\n2E,00\r\n30,0F\r\n" +
"FF,78,38,0A\r\n30,00\r\nFF,78,38,00\r\n28\r\n11\r\nFF,FF,FF,AA\r\nFF,78,38,08\r\n93,00\r\n8F,06\r\nFF,FF,FF,10\r\n93,C0\r\nFF,FF,FF,10\r\n93,00\r\n8F,C7\r\nFF,FF,FF,1\r\n93,C0\r\n";
                        txtCmd2.Text = "//2.RAM_TO_FLASH_FLOW_A（擦除）\r\nFF,78,38,19\r\nE0,18\r\nDF,55\r\nEE,10\r\nED,71\r\nEC,7C\r\nFF,FF,FF,1\r\nFF,78,38,00\r\n3A,07\r\n";
                    }
                    break;
                default: break;
            }
        }

        private void OpenTxtCode_Click(object sender, EventArgs e)
        {
            Button btn = (Button)sender;

            OpenFileDialog of = new OpenFileDialog();
            of.Filter = "文本文件(*.txt)|*.txt|所有文件(*.*)|*.*";
            of.Title = "初始化 Code";

            if (of.ShowDialog() == DialogResult.OK)
            {
                StreamReader streamReader = new StreamReader(of.FileName, Encoding.Default);
                switch (btn.Name)
                {
                    case "OpenTxtCode":
                        {
                            txtCmd1.Clear();
                            txtCmd1.Text = streamReader.ReadToEnd();
                        }
                        break;
                    case "OpenTxtCode2":
                        {
                            txtCmd2.Clear();
                            txtCmd2.Text = streamReader.ReadToEnd();
                        }
                        break;
                    case "OpenTxtCode3":
                        {
                            txtCmd3.Clear();
                            txtCmd3.Text = streamReader.ReadToEnd();
                        }
                        break;

                    default: break;
                }
                streamReader.Close();
            }
        }
        #endregion

        #region //BEST 模式 
        private void btnBISTGrayShow_Click(object sender, EventArgs e)
        {
            byte[] TepArr;
            byte GrayLevel;
            byte GrayLevel_1, GrayLevel_2;

            GrayLevel = byte.Parse(numPatternR.Value.ToString());
            GrayLevel_1 = (byte)((GrayLevel >> 1) & 0x60 + 4);
            GrayLevel_2 = (byte)((GrayLevel << 2) & 0xFC);

            TepArr = new byte[] {
                        4,0xff,0x78,0x38,0x02,
                        2,0xa2,0x00,
                        2,0x88,0x00,
                        2,0x89,0x00,
                        2,0x8a,0x10,
                        2,0x8b,0x00,
                        2,0x8c, GrayLevel_1 ,
                        2,0x8d, GrayLevel_2 ,
                        2,0xa5,0x01,
                       };
            try
            {
                frmHelp.comPort.Write(GetCRCArray(TepArr, 4), 0, TepArr.Length + 6);//循环部分，每段数据结尾                  
            }
            catch
            {
                MessageBox.Show("串口有误，请检查", "错误");
                return;
            }
        }
        static byte[] GetCRCArray(byte[] arr, Byte speedflag)
        {
            CRC16 CRCData = new CRC16();

            int arrNumbuer;                                                                                                                                                                                                                                                                                                                                             //51
            arrNumbuer = arr.Length;
            arrNumbuer += 6;
            byte[] Send_Datax = new byte[arrNumbuer];
            Send_Datax[0] = 0x9f;
            Send_Datax[1] = (byte)(speedflag << 4);
            Send_Datax[2] = Convert.ToByte(arr.Length + 1);  //为兼容下位机命令，此位置填待传输有效数据长度+1 

            Send_Datax[arr.Length + 3] = 0xFF;  //添加结束标志位
            arr.CopyTo(Send_Datax, 3);//合并数组头 4个Byte 标志位
            //计算校验码                                                 
            CRCData.CalculateCrc16(Send_Datax, out Send_Datax[arrNumbuer - 2], out Send_Datax[arrNumbuer - 1]);
            return Send_Datax;
        }
        //=================================LCD cfg function:OLED_Show_Click====Start=================
        private void OLED_Show_Click(object sender, EventArgs e)
        {
            if (!chkBISTMode.Checked)
            {
                Send_buf = new byte[25];
                Button btnTmp = (Button)sender;
                Setting.TempRecord.cmdLen = 25;
                Send_buf[0] = 0x0A; //LCD配置标志
                Send_buf[2] = 0x15; //数据长度
                switch (btnTmp.Name)
                {
                    case "btnPatternW":                             //写入Pattern参数
                        {
                            Send_buf[1] = 0x07;
                            Send_buf[3] = byte.Parse(numPatternR.Value.ToString());
                            Send_buf[4] = byte.Parse(numPatternG.Value.ToString());
                            Send_buf[5] = byte.Parse(numPatternB.Value.ToString());
                        }
                        break;
                    case "btnred":
                        {
                            Send_buf[1] = 0x07;
                            Send_buf[3] = 0xFF;
                            Send_buf[4] = 0;
                            Send_buf[5] = 0;
                        }
                        break; //R
                    case "btngreen":
                        {
                            Send_buf[1] = 0x07;
                            Send_buf[3] = 0;
                            Send_buf[4] = 0xFF;
                            Send_buf[5] = 0;
                        }
                        break; //G
                    case "btnblue":
                        {
                            Send_buf[1] = 0x07;
                            Send_buf[3] = 0;
                            Send_buf[4] = 0;
                            Send_buf[5] = 0xFF;
                        }
                        break; //B
                    case "btnwhite":
                        {
                            Send_buf[1] = 0x07;
                            Send_buf[3] = 0xFF;
                            Send_buf[4] = 0xFF;
                            Send_buf[5] = 0xFF;
                        }
                        break; //W
                    case "btnblack":
                        {
                            Send_buf[1] = 0x07;
                            Send_buf[3] = 0;
                            Send_buf[4] = 0;
                            Send_buf[5] = 0;
                        }
                        break; //BL
                    default:
                        {
                            Send_buf[1] = 0x07;
                            Send_buf[3] = 0xFF;
                            Send_buf[4] = 0xFF;
                            Send_buf[5] = 0xFF;
                        }
                        break;
                }

                CRCData.CalculateCrc16(Send_buf, out Send_buf[23], out Send_buf[24]);
                try
                {
                    frmHelp.comPort.Write(Send_buf, 0, 25);
                }
                catch
                {
                    MessageBox.Show("串口有误，请检查", "错误");
                }
                Thread.Sleep(8);
            }
            else
            {
                Button btnTmp = (Button)sender;
                byte[] TepArr;
                byte GrayLevel = 1; //white

                switch (btnTmp.Name)
                {
                    case "btnred":
                        {
                            GrayLevel = 4;  //red
                            txttip.Text += "---R---" + "\r\n";
                        }
                        break;
                    case "btngreen":
                        {
                            GrayLevel = 8;  //green
                            txttip.Text += "---G---" + "\r\n";
                            break;
                        }
                    case "btnblue":
                        {
                            GrayLevel = 0x10;
                            txttip.Text += "---B---" + "\r\n";
                            break;
                        }
                    case "btnwhite":
                        {
                            GrayLevel = 1;  //
                            txttip.Text += "---WHITE---" + "\r\n";
                        }
                        break;
                    case "btnblack":
                        {
                            GrayLevel = 2;  //
                            txttip.Text += "---BLACK---" + "\r\n";
                        }
                        break;

                    default: break;
                }

                TepArr = new byte[] {
                        4,0xff,0x78,0x38,0x02,
                        //2,0xa2,0x00,
                        2,0x88, GrayLevel,
                        2,0x89,0x00,
                        2,0x8a,0x00,

                        2,0x8c, 00 ,    //// SET FRAME DURATION 64 FRAME ~ 1S                       
                        2,0xa5,0x01,  // // BIST MODE ENABLE
                       };
                try
                {
                    frmHelp.comPort.Write(GetCRCArray(TepArr, 4), 0, TepArr.Length + 6);//循环部分，每段数据结尾                  
                }
                catch
                {
                    MessageBox.Show("串口有误，请检查", "错误");
                    return;
                }
            }
        }
        private void numPatternR_ValueChanged(object sender, EventArgs e)
        {
            if (checkBox1.Checked == true)
            {
                numPatternG.Value = numPatternR.Value;
                numPatternB.Value = numPatternR.Value;
            }
            btnBISTGrayShow.PerformClick();
            //Thread.Sleep(2);
        }
        #endregion

    }
}
